等待和异步行为
Await and async behavior
给出这个例子:
void Main() { Test().Wait(); }
async Task Test()
{
Console.WriteLine("Test A");
await AsyncFunction();
// It doesn't matter where the await is in AsyncFunction, it will always wait for the function to complete before executing the next line.
Console.WriteLine("Test B");
}
async Task AsyncFunction()
{
Console.WriteLine("AsyncFunction A");
await Task.Yield();
Console.WriteLine("AsyncFunction B");
}
绝不会在"AsyncFunction B"
之前显示"Test B"
Test() 中的 await 语句不只是等待 Task.Yield() 完成恢复,而是等待整个 AsyncFunction 完成?
In no case "Test B" will be displayed before "AsyncFunction B"?
不,那不会发生。
The await statement in Test() is not waiting just for Task.Yield() to finish to resume, but for the whole AsyncFunction to finish?
没错。由于您在 AsyncFunction
等待,一旦方法执行完毕,控制就会恢复。如果你没有等待它,那么下一行将在控制权从 await Task.Yield
返回后执行
给出这个例子:
void Main() { Test().Wait(); }
async Task Test()
{
Console.WriteLine("Test A");
await AsyncFunction();
// It doesn't matter where the await is in AsyncFunction, it will always wait for the function to complete before executing the next line.
Console.WriteLine("Test B");
}
async Task AsyncFunction()
{
Console.WriteLine("AsyncFunction A");
await Task.Yield();
Console.WriteLine("AsyncFunction B");
}
绝不会在"AsyncFunction B"
之前显示"Test B"Test() 中的 await 语句不只是等待 Task.Yield() 完成恢复,而是等待整个 AsyncFunction 完成?
In no case "Test B" will be displayed before "AsyncFunction B"?
不,那不会发生。
The await statement in Test() is not waiting just for Task.Yield() to finish to resume, but for the whole AsyncFunction to finish?
没错。由于您在 AsyncFunction
等待,一旦方法执行完毕,控制就会恢复。如果你没有等待它,那么下一行将在控制权从 await Task.Yield