multithreading – C# thread interruption stopped working – Education Career Blog

I dont know why but i can no longer interrupt my own thread.

thread = new Thread(new ParameterizedThreadStart(this.doWork));
thread.Start(param);
...
thread.Interrupt();
//in doWork()
try {
...
}
catch (System.Threading.ThreadInterruptedException)
{
//it never hits here. it use to
}

I search and i dont have any catch in my code and this is the only catch (System.Threading.ThreadInterruptedException). So what is going on? Using the debugger i can see my code run through the thread.Interrupt();. If i do thread.abort() i will catch a System.Threading.ThreadAbortException exception. Why is it catching that and not ThreadInterruptedException?

,

From BOL:

Interrupts a thread that is in the
WaitSleepJoin thread state.

If this thread is not currently
blocked in a wait, sleep, or join
state, it will be interrupted when it
next begins to block.

ThreadInterruptedException is thrown
in the interrupted thread, but not
until the thread blocks. If the thread
never blocks, the exception is never
thrown, and thus the thread might
complete without ever being
interrupted

BTW, you might be better off using the BackgroundWorker Class which supports cancelling.

,

From acidzombie24‘s comment to another answer:

So .abort is a better option? What i want to do is kill the thread but have it exist and call a few functions instead of outright death

Something like an event would be better.

Assuming you want to be able to signal each thread separately, before each worker thread is started create an AutoResetEvent and pass it to the thread.

When you want to interrupt the thread call Set on the event. In the worker thread check the state of the event regularly:

if (theEvent.WaitOne(TimeSpan.Zero)) {
  // Handle the interruption.
}

(Regularly: needs to be defined by the requirements: overhead of checking vs. latency of interruption.)

To have a master interrupt, to signal all workers, use a ManualResetEvent which will stay signalled, and keep interrupting threads when they check, until explicitly Reset.

Leave a Comment