static void Main(string[] args)
{
Console.WriteLine("我是主线程");
Task task =new Program(). Write1();
Console.Read();
}
private async Task Write1()
{
await Write2();
int po = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine(po);
Console.WriteLine("First async Run End");
}
private async Task Write2()
{
Console.WriteLine("Hello World!");
await Write3();
for (int i = 0; i < 3; i++)
{
int po = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine(po);
Console.WriteLine("Working..{0}", i);
await Task.Delay(1000);
}
}
private async Task Write3() {
for (int i = 0; i < 3; i++)
{
int po = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine(po);
Console.WriteLine("wirte3"+ i);
await Task.Delay(1000);
}
}
write3()里面的第一次循环为什么是在主线程中完成的,.为什么awiat Task.Delay(1000)后就会变成在另一个线程中执行.
加了await 关键字后,意味着异步线程被开启,这时程序就不会在主线程中执行了
但是 Write3()是在Write2()中调用的,前面也加了await关键字的,我开始以为Write3()的第一次循环就该是在另一个线程中执行.请指点一下
@请假一天: 如果你要使用 await Write2()调用整个Write3() 异步执行,那么就要改为如下:(也就是Write3()中无需再声明async)
private Task Write3()
{
for (int i = 0; i < 3; i++)
{
int po = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine(po);
Console.WriteLine("wirte3"+ i);
Task.Delay(1000);
}
}
请参考:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/task-asynchronous-programming-model
实际你 write1 里面 await Write2(); 写成
var task_write2 = Write2();
await task_write2();
你就会发现,主线程其实进了 Write2 方法,一直到 write3 方法里的 await Task.Delay(1000);才遇见第一个await,从此主线程返回。