是否在新Task()中等待Task.Delay(1000)阻塞某个线程?

时间:2020-03-25 06:38:25

标签: c# multithreading async-await

我已经阅读了一些文档,而我了解到await Task.Delay(1000)不会阻塞线程。

但是在此代码示例中,它似乎阻塞了线程:

       var task = new Task(async () => {
                Console.WriteLine(" ====== begin Delay()");
                for (int i = 1; i < 5; i++)
                {
                    Console.WriteLine(" ===Delay=== " + i);
                    Console.WriteLine("the task thread id: " + Thread.CurrentThread.ManagedThreadId + "; the task id is: " + Task.CurrentId);
                    await Task.Delay(1000);
                    Console.WriteLine("**ddd***:"+i);
                }

                Console.WriteLine(" ====== end Delay()");

            });

            task.Start();

它打印:

 ====== begin Delay()
 ===Delay=== 1
the task thread id: 3; the task id is: 1
**ddd***:1
 ===Delay=== 2
the task thread id: 4; the task id is:
**ddd***:2
 ===Delay=== 3
the task thread id: 3; the task id is:
**ddd***:3
 ===Delay=== 4
the task thread id: 4; the task id is:
**ddd***:4
 ====== end Delay()

根据打印输出,它以同步方式执行代码。

我认为它会打印如下内容:

 ====== begin Delay()
 ===Delay=== 1
the task thread id: 3; the task id is: 1    
 ===Delay=== 2
the task thread id: 4; the task id is:    
 ===Delay=== 3
the task thread id: 3; the task id is:    
 ===Delay=== 4
the task thread id: 4; the task id is:    
**ddd***:1
**ddd***:2
**ddd***:3
**ddd***:4
 ====== end Delay()

所以我很困惑,有人可以解释一下这种行为吗?谢谢。

1 个答案:

答案 0 :(得分:4)

在新Task()内部

首先,我必须说:never, ever use the Task constructor。有效用例完全为零。如果要在线程池线程上运行委托,请使用Task.Run

所以我很困惑,有人可以解释一下这种行为吗?

是的,关键是“命令式”(一步一步)和“同步”(阻止呼叫者)之间是有区别的。

根据打印输出,它以同步方式执行代码。

否,它根本不是同步的。但是,这势在必行。 When an await decides it needs to wait, it will "pause" its current method and return to the caller. When that await is ready to continue, it will resume executing its method.

请注意,该线程未被阻止。该方法已暂停。因此,这是必须的,但不是同步的。