开发者

What does resetAbort do?

开发者 https://www.devze.com 2023-03-05 00:37 出处:网络
Hi I have following test code: class Program { static void Main(string[] args) { Thread t = new Thread(Work);

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(ThreadAbortExc开发者_JAVA百科eption)
            {
                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!


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. The reason why "End" isn't output is because t.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 cancels the abort request for a thread

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号