I’m programming a plug-in for a large system. The systems runs my plug-in in an independent thread. Inside the plug-in I’m allocating an unmanaged resource. I need to be 100% sure I release this driver. I implemented the IDisposable pattern and I covered all methods the system claims to call if the plug-in is about to be terminated.
I’m a bit worried about the situation, when the system for any reason quits my thread (Abort, or whatever). Could I do something more in my plug-in to ensure the unmanaged resource will be released?
E.g. if I push stop debugging in VS, the resource remains unreleased (I know it’s a stupid example).
This is actually a pretty confusing topic. One reason why we all harp about
Thread.Abortis because it injects an asynchronous exception into the target thread. The injection is nondeterministic and can often be at an unsafe point. It could occur immediately after acquiring a resource (lock, unmanaged resource, etc.) causing a resource leak or leaving a lock in an acquired state. The CLR has some provisions for mitigating the risk by attempting to delay the injection in some very intricate ways during the execution of try-catch-finally blocks. Unfortunately, there is no fail-safe way to guarentee all of the scenarios involved when callingThread.Abortand I suspect the vast majoring of the edge cases lie in the unmanaged code realm. For this reason I advise against aborting threads.Instead your should design your plugin so that it runs in a separate
AppDomainand accepts shutdown requests so that it has a chance to gracefully end on its own. There would be some marginal level of protection by using a separate application domain since you could, as a last resort, abort a misbehaving thread and then tear down theAppDomainin which the thread was executing code. Again, there is no guarentee that this will completely isolate the potential for corrupted state caused by the abort. The only fail-safe design is to run the plugin in its own process.Unrelated to the abort problem there a couple of things you need to do to make sure the unmanaged resource is released. First, implement a finalizer so that in the absence of calling
Disposethe finalizer should do it eventually. Second, and I am not sure what level of protection this actually provides, callGC.SuppressFinalizeafter the call to the privateDispose(bool)method. If an ansynchronous exception were to get injected in the publicDisposemethod you do not want the object removed from the finalization queue. Again, I am not sure how much that is going to help because your object may now be in a corrupted state which would prevent the second attempt at releasing the resource. Third, if possible use one of theCriticalFinalizerObjectorSafeHandleclasses to wrap the resource as this adds further protection through the use of Constrained Execution Regions.