简体   繁体   中英

Putting main thread to sleep has no effect on Task.Run, why?

I designed a Window From application to see whether an async method still works if the main thread goes sleep. Here it is:

1- By click of Async button, AsyncMethod is awaited on.

2- By click of Sleep button, main thread sleeps.

I know how awaiting AsyncMethod works: using a state machine, it returns back to the caller but it is still working and alive. I don't have any problem with it. Simple and neat!

What I don't understand is where and by which thread this method is executed. Why putting main thread to sleep doesn't suspend AsyncMethod ?

在此处输入图片说明

Here is the code:

        private async void btnAsync_Click(object sender, EventArgs e)
        {
            await AsyncMethod(TimeSpan.FromSeconds(10));
        }

        private void btnSleep_Click(object sender, EventArgs e)
        {
            Thread.Sleep(TimeSpan.FromSeconds(10));
        }
        public async Task AsyncMethod(TimeSpan duration)
        {
            await Task.Run(() =>
            {
                DateTime start = DateTime.Now;
                TimeSpan ellapsed = DateTime.Now - start;
                int lastReport = 0;
                Console.Write("Working");
                while (ellapsed < duration)
                {
                    ellapsed = DateTime.Now - start;
                    if (lastReport < Math.Ceiling(ellapsed.TotalSeconds))
                    {
                        lastReport = (int)Math.Ceiling(ellapsed.TotalSeconds);
                        Console.Write(".");
                    }
                }
                Console.Write("Finished");
            });
        }

What I don't understand is where and by which thread this method is executed. Why putting main thread to sleep doesn't suspend AsyncMethod?

This method is executed by a thread from the CLR's managed threads pool. If this was true, then the main thread in your application, which is responsible for your UI would be frozen, while it was working on the execution of you async method and the UI exprerience wouldn't be the best one.

Furthermore, this is the purpose of Task.Run method. According to MSDN

Queues the specified work to run on the ThreadPool and returns a task or Task handle for that work.

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