How to handle ThreadInterruptedException?

public void threadMethod() { try { // do something } catch (ThreadInterruptedException e) { Console.WriteLine("[Net]", role, "Thread interrupted."); n.CloseConnection(); } finally { if (isAutenticated == false) { n.CloseConnection(); } Dispatcher.Invoke(addMessage, "Network connection searching was disabled."); DebuggerIX.WriteLine("[Net]", role, "Finished"); Dispatcher.Invoke(threadStoppedDel); } } 

The threadMethod method is launched through System.Threading.Thread. A thread can be interrupted whenever a ThreadInterruptedException can be thrown into a finally block, right? Should I wrap the block in try-catch again?

Thanks!

+6
exception-handling finally
source share
1 answer

Interruption of a thread is interrupted when the thread is interrupted by manually calling Thread.Interrupt . Windows itself will not interrupt the stream using this method. Typically, your program will monitor when a thread sends an interrupt (not all the time). Since the interrupt signal can be used for some flow control, it is usually not sent twice in quick succession.

A ThreadInterruptedException is thrown into the interrupted thread, but only until the thread blocks. If the thread never blocks, an exception is never thrown, and thus the thread can terminate without interruption.

If your thread never sleeps or waits for other objects (entering the WaitSleepJoin state), you will never see an exception thrown.

Protecting your flow, as you should, should be acceptable. Remember that a ThreadAbortException can also be thrown, and they are a bit more common and can be thrown more often (application closes, etc.).

+7
source share

All Articles