Search code examples
c#.net.net-4.0disposefinalizer

Execute code when VisualStudio debugger is exiting


I had assumed that when terminating debugging (such as by hitting the Stop button, or hitting Shift+F5), that any class implementing a finalizer or IDisposable would be, well, disposed.

I have some classes that implement IDisposable. There are a few things I'd like to (try) and do as the application exits from the debugger (or from crashing in production). Right now, Dispose() does not appear to be called, nor a finalizer ~MyClass(){}

Is there a way to do this?


Solution

  • For normal stopping of Windows services, you should put your code in your Stop method.

    http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.stop.aspx

    In general, rude thread aborts and rude app domain unloads aren't going to run 'normal' finalizers - you can get more details in this MSDN article.

    https://web-beta.archive.org/web/20150423173148/https://msdn.microsoft.com/en-us/magazine/cc163716.aspx

    Up to this point, I've simply talked about thread aborts as the result of the runtime throwing ThreadAbortException on a thread. Typically, this will cause the thread to terminate. However, a thread can handle a thread abort, preventing it from terminating the thread. To account for this, the runtime provides a more powerful action, the aptly named rude thread abort. A rude thread abort causes a thread to cease execution. When this happens, the CLR makes no guarantees that any back-out code on the thread will run (unless the code is executing in a CER). Rude, indeed.

    Similarly, while a typical application domain unload will gracefully abort all threads in the domain, a rude application domain unload will rudely abort all threads in the domain, and makes no guarantees that normal finalizers associated with objects in that domain will run. SQL Server 2005 is one CLR host that makes use of rude thread aborts and rude application domain unloads as part of its escalation policy. When an asynchronous exception occurs, the resource allocation failure will be upgraded to a thread abort. And when a thread abort occurs, if it doesn't finish within a time span set by SQL Server, it'll be upgraded to a rude thread abort. Similarly, if an application domain unload operation does not finish within a time span set by SQL Server, it'll be upgraded to a rude application domain unload. (Note that the policies just laid out are not exactly what SQL Server uses, as SQL Server also takes into account whether code is executing in critical regions, but more on that topic shortly).