Thursday, July 31, 2008

Prevent Thread Abort-ion with Critical-ity

If you've gone all the way to implement threading in your .NET application, you might be wondering what would happen to an atomic operation in the thread when Thread.Abort is called. Let's say you're performing an operation and storing the count of something in another variable - you've got to make sure that the values are consistent.

That's when you would use Thread.BeginCriticalRegion and Thread.EndCriticalRegion. While your thread is in a critical region, it will not abort till the critical code has executed.

As a side note, I'd like to mention that Microsoft also tells you to avoid the non-blocking Thread.Suspend() call because it only causes the thread to suspend at the next safe point for garbage collection. In other words, it means that the suspend is not immediate and can occur at some future time.

No comments: