c# - 当我不能使用 ConfigureAwait(false) 时?

标签 c# .net asynchronous async-await task-parallel-library

根据最佳实践,如果可以的话,建议使用 .ConfigureAwait(false)async/await 关键字:

await Task.Run(RunSomethingAsync).ConfigureAwait(false);

能否请您举例说明我无法使用 .ConfigureAwait(false) 的情况?

最佳答案

当您真正关心您所在的同步上下文时,您“不能”使用ConfigureAwait(false)。例如,想象一下 GUI 应用程序中的以下内容:

public async void SomeButtonClick(object sender, EventArgs e)
{
    var result = await SomeAsyncOperation().ConfigureAwait(false);
    textBox.Text = result;
}

当您从 ConfigureAwait 返回时,您将不会回到 UI 线程。这将导致 InvalidOperationException

关于c# - 当我不能使用 ConfigureAwait(false) 时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32377028/

相关文章:

c# - 如何更改任务中的值

c# - DataGridView 缺少数据源为空的新行

c# - 在.NET 中,委托(delegate)的内部实现是什么?

c# - 如何在 C# 6 中使用带字符串插值的转义字符?

.net - 如何将 AutoCompleteExtender 设置为仅允许自动完成列表中的值?

angular - 使用 RXJS 继续以 Angular 触发 http 调用,直到满足条件

javascript - js 异步使用数组 push() shift()

c# - 在 C# 中,我无法将 XML 反序列化为对象

c# - 在 C# 中验证一个字符串是否只包含字母

c# - 如何确定代码块的范围?