简体   繁体   English

resetAbort是做什么的?

[英]What does resetAbort do?

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. 每次中止时,都会执行Thread.ResetAbort()。 I wonder what this ResetAbort does. 我不知道此ResetAbort会做什么。 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. 而且我没有看到输出“ End”-看来该程序根本没有结束。 Do you know why? 你知道为什么吗? Thanks! 谢谢!

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. 因此,在这种情况下,循环将继续进行,线程仍应处于活动状态。

The others' answer about ResetAbort is correct. 其他人对ResetAbort的回答是正确的。 The reason why "End" isn't output is because t.Join() never returns. 之所以不输出“ End”,是因为t.Join()从不返回。 This is because your thread is only attempted to be aborted three times, and your loop contains 10 attempts at infinite loops. 这是因为您的线程仅被尝试中止3次,并且您的循环在无限循环中包含10次尝试。 Join returns when the target thread completes running its delegate, and yours doesn't complete. 当目标线程完成其委托运行,而您的委托未完成时, Join返回。

ResetAborts取消线程的中止请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM