views:

47

answers:

4

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).

+1  A: 

Under .NET, there is no way to have code run when a thread terminates. The best you can do is write a finalizer, and hope it gets called within a reasonable time frame.

Anthony Williams
+1  A: 

You need to implement both a finalizer and IDisposable so that if for any reason Dispose is not called (thread abort), GC would release it.

So your finalizer will call your Dispose method:

class MyClass : IDisposable
{
    public void Dispose()
    {
        Dispose(true);
    }

    private void Dispose(bool disposing)
    {
        // release ...
    }

    ~MyClass()
    {
        Dispose(false);
    }
}

Reason for passing disposing is that you know not to touch any state if it is finalizing.

Aliostad
This is exactly what I have implemented so far (= the IDisposable pattern), I'd like to know if it ensures the release of the unmanaged resource. And what can I do if it doesn't.
GC by definition is not deterministic. So you would not know when it is released. You can put GC.Collect() wherever you feel thread abort could have happened. If CLR crashes for some reason or power failure then there is nothing you could do.
Aliostad
+1  A: 

Try catching this exception: http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx

And do a disposing there if the resource has not been disposed.

Pablo Castilla
A: 

This is actually a pretty confusing topic. One reason why we all harp about Thread.Abort is 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 calling Thread.Abort and 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 AppDomain and 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 the AppDomain in 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 Dispose the finalizer should do it eventually. Second, and I am not sure what level of protection this actually provides, call GC.SuppressFinalize after the call to the private Dispose(bool) method. If an ansynchronous exception were to get injected in the public Dispose method 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 the CriticalFinalizerObject or SafeHandle classes to wrap the resource as this adds further protection through the use of Constrained Execution Regions.

Brian Gideon