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 method threadMethod is run via System.Threading.Thread. The thread may be interrupted whenever therefore the exception ThreadInterruptedException may be thrown in finally block, right? Do I have to enclose the block in finally in try-catch again?
Thanks!
A thread interrupted exception is thrown when the thread is interrupted by manually calling Thread.Interrupt. Windows itself won't interrupt your thread using that method. Generally it will be your program in control of when a thread is sent the interrupt signal (not all the time). Since the interrupt signal can be used for some flow control it usually isn't sent twice in a fast succession.
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.
If your thread never sleeps or waits on other objects (entering a WaitSleepJoin state) you'll never see the exception thrown.
Protecting your thread as you have should be acceptable. Don't forget that a ThreadAbortException can be thrown too, and those are slightly more pervasive and can be thrown more often (application is shutting down, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With