等待和异步行为

2 .net c# asynchronous task-parallel-library async-await

鉴于这个例子:

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");
}
Run Code Online (Sandbox Code Playgroud)

在任何情况下都不会在"AsyncFunction B"之前显示"Test B"

Test()中的await语句不是等待Task.Yield()完成恢复,而是整个AsyncFunction完成?

Yuv*_*kov 7

在任何情况下,"AsyncFunction B"之前都不会显示"Test B"?

不,那不会发生.

Test()中的await语句不是等待Task.Yield()完成恢复,而是整个AsyncFunction完成?

那就对了.由于您正在等待AsyncFunction,一旦方法完成执行,控制将恢复.如果你没有等待它,那么一旦控制返回,就会执行下一行await Task.Yield

  • @Nathan没有多少.但更多的是[这里](http://stackoverflow.com/questions/22645024/when-would-i-use-task-yield)和[here](http://stackoverflow.com/questions/23431595/task -yield实时的用途/ 23441833#23441833).所有它基本上都是将延续发布到当前同步上下文. (2认同)