重置中止有什么作用?
您好,我有以下测试代码:
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(Work);
t.Start();
Thread.Sleep(1000);
t.Abort();
Thread.Sleep(1000);
t.Abort();
Thread.Sleep(1000);
t.Abort();
t.Join();
Console.WriteLine("End");
}
static void Work()
{
int i = 0;
while (i<10)
{
try
{
while(true);
}
catch(ThreadAbortException)
{
Thread.ResetAbort();
}
Console.WriteLine("I will come back!");
i++;
}
}
}
每次发生中止时,都会执行 Thread.ResetAbort() 。我想知道这个 ResetAbort 是做什么的。因为当我运行它时,我看到了以下输出: 我会回来的! 我会回来的! 我会回来的! 而且我没有看到输出“End”——看来这个程序根本没有结束。你知道为什么吗?谢谢!
Hi I have following test code:
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(Work);
t.Start();
Thread.Sleep(1000);
t.Abort();
Thread.Sleep(1000);
t.Abort();
Thread.Sleep(1000);
t.Abort();
t.Join();
Console.WriteLine("End");
}
static void Work()
{
int i = 0;
while (i<10)
{
try
{
while(true);
}
catch(ThreadAbortException)
{
Thread.ResetAbort();
}
Console.WriteLine("I will come back!");
i++;
}
}
}
Everytime, when there is an abort, Thread.ResetAbort() will be executed. I wonder what this ResetAbort does. Because when I run it, I saw the following output:
I will come back!
I will come back!
I will come back!
And I didn't see the output "End" - it seems this program didn't end at all. Do you know why? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它取消中止线程的请求。 如此处所示。 因此在这种情况下循环将继续,并且线程应该仍然存在。
It cancels the request to abort the thread. As indicated here. So in this case the loop will continue and the thread should still be alive.
其他人关于
ResetAbort
的回答是正确的。不输出“End”的原因是t.Join()
永远不会返回。这是因为您的线程仅尝试中止 3 次,而您的循环包含 10 次无限循环尝试。当目标线程完成运行其委托时,Join
返回,而您的委托未完成。The others' answer about
ResetAbort
is correct. The reason why "End" isn't output is becauset.Join()
never returns. This is because your thread is only attempted to be aborted three times, and your loop contains 10 attempts at infinite loops.Join
returns when the target thread completes running its delegate, and yours doesn't complete.ResetAborts 取消线程的中止请求
ResetAborts cancels the abort request for a thread