Mar*_*cka 7 .net exception-handling finally
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);
}
}
Run Code Online (Sandbox Code Playgroud)
threadMethod方法是通过System.Threading.Thread运行的.线程可能会被中断,因此可能会在finally块中抛出异常ThreadInterruptedException,对吧?我是否必须再次将该块封装在try-catch中?
谢谢!
当线程被手动调用Thread.Interrupt中断时,抛出线程中断的异常.Windows本身不会使用该方法中断您的线程.通常,您的程序将控制线程何时发送中断信号(而不是所有时间).由于中断信号可用于某些流量控制,因此通常不会快速连续发送两次.
ThreadInterruptedException在被中断的线程中抛出,但直到线程阻塞.如果线程永远不会阻塞,则永远不会抛出异常,因此线程可能会完成而不会被中断.
如果你的线程从不休眠或等待其他对象(进入WaitSleepJoin状态),你将永远不会看到抛出的异常.
保护您的线程应该是可以接受的.不要忘记也可以抛出ThreadAbortException,并且这些更普遍,并且可以更频繁地抛出(应用程序正在关闭等).