Monday, December 10, 2012

Using, Exceptions and Ctrl+C

Many people believe that when they use a using statement a Dispose method is always going to be called, and they are safe to clear resources there. For investigation reasons I also included Catch and Finally statements, because Using statement can be thought of as a following code:
try
{
    // A code inside using statement
}finall{
    // A dispose method
}
As seen in an example above using is not rethrowing an exception, or stopping it, it is just letting it go.

Let us consider a code below:
static void Main(string[] args)
{
    Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler);

    try
    {
        using (new DisposableClass())
        {
            while (true) { 

            }
        }
    }
    catch
    {
        Console.WriteLine("Catch");
    }
    finally {
        Console.WriteLine("Finally");
    }
}

protected static void myHandler(object sender, ConsoleCancelEventArgs args)
{
    Console.WriteLine("myHandler intercepted");
}
Where a DisposableClass is listed below
public class DisposableClass : IDisposable
{
    public void Dispose() {
        Console.WriteLine("Dispose");
    }
}
Many people forget that there are other methods to interrupt an application than exceptions (i.e. forcefully aborting a thread). An example is an good old SIGINT signal, also known as Ctr+C. If application is executing a code above, and is in a while loop. And someone presses Ctr+C than Dispose method, catch, finally blocks are not going to be called. If there is a need to intercept this signal, one needs to signup for a CancelKeyPress event, just as in a code above. In other words, after pressing Ctr+C the only line that is going to be displayed is:
myHandler intercepted
A next example of not executing Using/Catch/Finally block is by running
Thread.Abort()
For majority of cases the block will be executed, but when a thread is nearly finished, and it entered a Finally block, and then someone calls Thread.Abort(), then Finally block is not going to be executed.

No comments: