简体   繁体   English

使主线程进入睡眠状态对Task.Run没有影响,为什么?

[英]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. 我设计了一个Window From应用程序,以查看如果主线程进入睡眠状态, async方法是否仍然有效。 Here it is: 这里是:

1- By click of Async button, AsyncMethod is awaited on. 1-通过单击异步按钮,等待AsyncMethod

2- By click of Sleep button, main thread sleeps. 2-单击“睡眠”按钮,主线程进入睡眠状态。

I know how awaiting AsyncMethod works: using a state machine, it returns back to the caller but it is still working and alive. 我知道等待AsyncMethod工作方式:使用状态机,它返回给调用者,但仍在工作并且仍然存在。 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 ? 为什么将主线程置于睡眠状态不会暂停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? 为什么将主线程置于睡眠状态不会暂停AsyncMethod?

This method is executed by a thread from the CLR's managed threads pool. 该方法由CLR的托管线程池中的线程执行。 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. 如果这是真的,那么应用程序中负责UI的主线程将被冻结,而该线程正在执行异步方法,并且UI体验不是最好的。

Furthermore, this is the purpose of Task.Run method. 此外,这是Task.Run方法的目的。 According to MSDN 根据MSDN

Queues the specified work to run on the ThreadPool and returns a task or Task handle for that work. 将指定的工作排队以在ThreadPool上运行,并返回该工作的任务或任务句柄。

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

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