Good Night Nerd Pride
Good Night Nerd Pride

Reputation: 8442

Async methods with and without async modifier

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

Upvotes: 4

Views: 250

Answers (2)

Rob Lyndon
Rob Lyndon

Reputation: 12651

Add1 will run synchronously until it encounters the await keyword. In this case, that will not have an effect because the await keyword is at the beginning of the method.

To see the effect of this, you can insert a Thread.Sleep() method into the beginning of Add1 and Add2, and notice that the method marked async blocks before it returns.

Upvotes: 1

Stephen Cleary
Stephen Cleary

Reputation: 456322

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.

Upvotes: 6

Related Questions