简体   繁体   中英

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. 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取消线程的中止请求

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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