我怎么知道异步方法调用是否会改变调用者的上下文?

mat*_*lat 5 c# ui-thread async-await

考虑这个例子:

async Task Foo()
{
    button.Text = "This is the UI context!";

    await BarA();

    button.Text = "This is still the UI context!";

    await BarB();

    button.Text = "Oh no!"; // exception (?)
}

async Task BarA()
{
    await Calculations();
}

async Task BarB()
{
    await Calculations().ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)

如何await BarB()读取async Task BarB()函数体的情况更改上下文?我是否真的需要确切知道异步函数是否ConfigureAwait(false)在任何时候调用?或者这个例子可能是错误的并且没有例外?

Mar*_*ell 9

BarB()除非BarB()需要与UI交谈,否则什么是无关紧要的.这里的重要部分是await在线:

await BarB();
Run Code Online (Sandbox Code Playgroud)

await捕捉上下文(太) -和协商得到到正确的上下文,如果它发现自己在不断错误的上下文.所以; 除非你写:

await BarB().ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

你应该没事.

ConfigureAwait(false)BarB()看起来正常的,可能是正确的,如果我们假设BarB()并不需要直接更新UI或执行任何其他上下文绑定操作.