异步方法瓦特/和W / O异步修饰符 [英] Async methods w/ and w/o async modifier
问题描述
有什么方法之间的区别 ADD1()
和 ADD2()
?有没有在所有的区别吗?据我所知,使用(如图方法 UsageTest()
)是一样的。
专用异步任务< INT> ADD1(INT A,INT B)
{
返回等待Task.Run(
()=>
{
Thread.sleep代码(1000);
返回A + B;
});
}私人任务< INT> ADD2(INT A,INT B)
{
返回Task.Run(
()=>
{
Thread.sleep代码(1000);
返回A + B;
});
}私人异步无效UsageTest()
{
诠释一个=等待ADD1(1,2);
INT B =等待ADD2(1,3);
}
语义上讲,它们几乎等价的。
的主要区别是, ADD1
有更多的开销(用于异步
状态机)。
还有一个较小的差异; ADD1
将元帅回到原来的环境,而 ADD2
不会。这可能会导致死锁如果调用code不使用等待
:
公共无效的button1_Click(..)
{
。ADD1()等待(); //死锁
。ADD2()等待(); //不会死锁
}
我更详细地解释这种死锁情况在我的博客和在最近MSDN文章。
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.
The main difference is that Add1
has more overhead (for the async
state machine).
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
}
I explain this deadlock situation in more detail on my blog and in a recent MSDN article.
这篇关于异步方法瓦特/和W / O异步修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!