SamFisher83
SamFisher83

Reputation: 3995

how to catch ThreadAbort?

I have a function where I call thread.abort to kill a thread. I know this isn't the best practice, but I am calling a function in a dll which basically has an infinite loop in that function so the only way I can terminate the thread is to call a thread abort. I can call a thread.join, but then my my gui will get stuck. I have done a catch in both my form application and in that thread, but when I call the thread.abort function an exception is thrown which is caught by my try block in one of those places, but my application still crashes.

What is the proper way to handle a threadAbort so it doesn't crash my application.

Upvotes: 1

Views: 176

Answers (2)

Samuel Neff
Samuel Neff

Reputation: 74909

Don't use Thread.Abort(), signal the thread to stop. Something like

private volatile _keepRunning = true;

public void DoWork()
{
    while(_keepRunning)
    {
    }
}

public void Abort()
{
    _keepRunning = false;
}

You can get more fancy with ManualResetEvents to signal an end quicker and still use a join, but basic concept is there. I use this often in our apps, it works well.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754763

Your application is crashing because a ThreadAbortException is automatically rethrown at the end of any catch block that handles it. To prevent it from being rethrown you need to call Thread.ResetAbort().

try {
  ...
} catch (ThreadAbortException) {
  Thread.ResetAbort();
}

Note: I'd advise you to find another way to get out of this method. Aborting a thread is very dangerous and should be only a mechanism of last resort. It would be much safer to pass a cancelation token to the thread or use a shared flag to exit the infinite loop.

Upvotes: 6

Related Questions