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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With