c# - 带有和不带有 async 修饰符的异步方法

标签 c# async-await

方法 Add1()Add2() 有什么区别?有区别吗?据我所知,用法(如方法 UsageTest() 所示)是相同的。

private async Task<int> Add1(int a, int b)
{
    return await Task.Run(
        () =>
            {
                Thread.Sleep(1000);
                return a + b;
            });
}

private Task<int> Add2(int a, int b)
{
    return Task.Run(
        () =>
            {
                Thread.Sleep(1000);
                return a + b;
            });
}

private async void UsageTest()
{
    int a = await Add1(1, 2);
    int b = await Add2(1, 3);
}

最佳答案

在语义上,它们实际上是等价的。

主要区别是 Add1 有更多开销(对于 async 状态机)。

还有一个较小的区别; Add1 将编码回其原始上下文,而 Add2 则不会。如果调用代码不使用 await,这可能会导致死锁:

public void Button1_Click(..)
{
  Add1().Wait(); // deadlocks
  Add2().Wait(); // does not deadlock
}

我更详细地解释了这种死锁情况on my blogin a recent MSDN article .

关于c# - 带有和不带有 async 修饰符的异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16987798/

相关文章:

c# - ASP.Net Identity - AddLogin userId 变为 null

c# - 本地化与定制

asynchronous - EF6 - 在 Where() 子句中使用 await 关键字

c# - FromBluetoothAddressAsync IAsyncOperation 不包含 'GetAwaiter' 错误的定义

c# - .ContinueWith() 的竞争条件

c# - 使用 PageMethods 从 Javascript 代码调用 C# bool 函数

c# - 防止 WebBrowser 在导航时导致 UI 卡住?

C# 在方法参数内等待

c# - 如何通过Escape键正确取消并行异步IO任务?

c# - 无法生成:Microsoft/aspnetcore的 list :2.1找不到Visual Studio 7.5.2 Mac OS X