Reputation: 2064
What happens after a thread.Abort() ??
Say i have:
Thread mWorker = new Thread(new ThreadStart(this.run));
..
mWorker.Start();
**where**
private void run()
{
Logger.d(TAG, "run()");
...
try {
while (this.mRunning){
...
}
} catch (ThreadAbortException tae){
Logger.e(TAG,"some msg", tae);
this.doSomething();
} catch (IOException ioe){
Logger.e(TAG,"some msg", ioe);
this.doSomething();
} catch (Exception e){
Logger.e(TAG,"some msg", e);
this.doSomething();
} finally {
gracefoulyClose();
}
Logger.d(TAG, "run() - ended");
}
Thread is more complex.. but the esential is displayed here. So what happens when Abort() gets called? will my catch work and continue with the call of doSomething()?
Because i still receive in console:
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
An exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll but was not handled in user code
But i do have a catch for that. Don't I ??
Upvotes: 4
Views: 14735
Reputation: 1022
If you are using some where in code response.redirect();
then it will internally
run thread.abort();
so it will throw exception.Instead of that you can use Response.Redirect(url,false);
Upvotes: 1
Reputation: 746
You are getting a ThreadAbortException because your context is exiting before the thread is finished running. You need to wait on the thread to complete before you exit. If you want to exit, you need to make sure that your thread can receive a signal (and act upon it) that your program wishes to end, and then your code that manages program execution must wait on the thread to complete:
if (mThread != null && mThread.IsAlive) {
mThread.Join();
}
Use the overload with the timeout if you're worried about the thread never exiting, and kill the thread explicitly if you hit the timer.
Upvotes: 0
Reputation: 55444
From the doc:
When a call is made to the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread. Because the thread can do an unbounded computation in the finally blocks or call Thread.ResetAbort to cancel the abort, there is no guarantee that the thread will ever end. If you want to wait until the aborted thread has ended, you can call the Thread.Join method. Join is a blocking call that does not return until the thread actually stops executing.
So in other words, after your catch block for the ThreadAbortException
executes, the exception is re-raised, so your last logger line (e.g. Logger.d(TAG, "run() - ended")
) never executes. But since the call to this.doSoemthing
is in the catch block for the ThreadAbortException
, it will execute.
Note also that, your finally
block does execute (refer to doc above).
Upvotes: 7