This post originated from an RSS feed registered with .NET Buzz
by Doug Thews.
Original Post: Should You Call Thread.Abort?
Feed Title: IlluminatiLand
Feed URL: http://apps5.oingo.com/apps/domainpark/domainpark.cgi?client=netw8744&s=JETBRAINS.COM
Feed Description: A technology blog for people enlightened enough to think for themselves
There's a lot of mis-information about how to cancel a worker thread. A lot of articles (including some MSDN documentation) shows calling Thread.Abort() in the main thread, followed by a Thread.Join() call to block the thread until the worker thread ends. Then, in the worker thread, you wrap your entire code section with Try...Catch and catch the ThreadAbortedException.
However, some C# MVPs in the Microsoft news group have told me that this may actually lead to the crash of your AppDomain, or at minimum cause instability within your application.
Instead, they recommend using Thread.Interrupt() to generate a "soft" interrupt in your worker thread, and handle the ThreadInterruptedException instead of the ThreadAbortedException to gracefully exit from the worker thread.
One thing is for sure ... you need to make sure to do all of your worker thread cleanup within this exception handling code. if you don't, there's a chance that your thread could stay active and resident. You can use Task Manager (and add Thread Count to the column view) to see if your application is still resident after you think you've closed it. Thread Count is a very useful value to determine how many threads your application actually has active at any given point in time.