4

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.