【发布时间】: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()
所以我很困惑,有人可以解释一下这种行为吗?谢谢。
【问题讨论】:
-
您似乎混淆了两件不同的事情。在继续之前等待进程完成并不一定等于阻塞线程。当你使用
await AnyTrueAsyncMethod();时,线程不会被阻塞,但是下一行不会被执行,直到任务完成。 -
@IvanYang 您的代码未执行并不意味着当前线程被“阻塞”。见stackoverflow.com/a/34706101/4123703
标签: c# multithreading async-await