具有和不具有异步修饰符的异步方法 [英] Async methods with and without async modifier
问题描述
方法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屋!