gpt4 book ai didi

C#线程中断停止工作

转载 作者:行者123 更新时间:2023-11-30 21:25:19 28 4
gpt4 key购买 nike

我不知道为什么,但我不能再打断我自己的话题了。

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
}

我搜索了一下,我的代码中没有任何问题,这是唯一的问题 (System.Threading.ThreadInterruptedException)。那么发生了什么?使用调试器,我可以看到我的代码通过 thread.Interrupt(); 运行。如果我执行 thread.abort() 我将捕获 System.Threading.ThreadAbortException 异常。为什么它捕获那个而不是 ThreadInterruptedException?

最佳答案

来自 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

顺便说一句,您最好使用支持取消的 BackgroundWorker 类。

关于C#线程中断停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/718564/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com