Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async methods with and without async modifier

Tags:

c#

async-await

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);
}
like image 702
Good Night Nerd Pride Avatar asked Mar 23 '23 15:03

Good Night Nerd Pride


1 Answers

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.

like image 90
Stephen Cleary Avatar answered Mar 31 '23 17:03

Stephen Cleary