Friday, February 4, 2011

Is there a way to ensure entire code block execution in a .NET thread?

In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch ThreadAbortedException, do Thread.ResetAbort() and die beautifully (that is, the thread).

The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner:

try {
} finally {
  // vital code
}

However, I didn't find any other solution.

Is this another way to delay the interference of ThreadAbortException until the end of the block?

  • The situations under which a ThreadAbortException will be generated can be complex. A better option might be to ask why you are using ThreadAbortExceptions at all.

    A better pattern would be to simply use a flag to indicate to the running thread that it should abort, and then test the flag regularly while it is working. If it is set you can throw an exception at that point if you want.

    With this pattern you are totally in control of when the thread will act on the abort, and don't have to worry about the critical operations being interrupted.

    From Rob Walker
  • Use Thread.BeginCriticalRegion()

    Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.

    Thread.BeginCriticalRegion()
    
    //do important stuff here
    
    Thread.EndCriticalRegion()
    
    André Neves : Although BeginCriticalRegion() might, in a way, ensure code execution, because your application could halt otherwise, I wanted a device which disallowed ThreadAbortExceptions from interrupting my code.
    From Corey

0 comments:

Post a Comment