具有和不具有异步修饰符的异步方法 [英] Async methods with and without async modifier

查看:66
本文介绍了具有和不具有异步修饰符的异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the difference between methods Add1() and Add2()? Is there a difference at all? For all I know usage (as shown in method UsageTest()) is the same.

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);
}

推荐答案

从理论上讲,它们实际上是等效的.

Semantically, they are practically equivalent.

主要区别在于Add1的开销更大(对于async状态机).

The main difference is that Add1 has more overhead (for the async state machine).

差异也较小; Add1将编组回其原始上下文,而Add2则不会.如果调用代码不使用await,则可能导致死锁:

There is also a smaller difference; Add1 will marshal back to its original context while Add2 will not. This can cause a deadlock if the calling code does not use await:

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

我在博客上更详细地解释了这种僵局情况在最近的MSDN文章中.

I explain this deadlock situation in more detail on my blog and in a recent MSDN article.

这篇关于具有和不具有异步修饰符的异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆