【问题标题】:Does await Task.Delay(1000) inside new Task() block some thread?new Task() 中的 await Task.Delay(1000) 是否会阻塞某些线程?
【发布时间】:2020-03-25 06:38:25
【问题描述】:

我阅读了一些文档,了解到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()

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

【问题讨论】:

  • FYI
  • 您似乎混淆了两件不同的事情。在继续之前等待进程完成并不一定等于阻塞线程。当你使用await AnyTrueAsyncMethod(); 时,线程不会被阻塞,但是下一行不会被执行,直到任务完成。
  • @IvanYang 您的代码未执行并不意味着当前线程被“阻塞”。见stackoverflow.com/a/34706101/4123703

标签: c# multithreading async-await


【解决方案1】:

在 new 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.

注意线程没有被阻塞。该方法已暂停。所以它是命令式的,但不是同步的。

【讨论】:

    猜你喜欢
    • 2015-11-08
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多