2

Can anyone explain why async functions in c# 5 are required to have at least 1 await? I can't find a clear reason/explaination.

By required, I mean that the compiler warns when an async function doesn't have any await calls inside of it, but doesn't throw a compile error.

From this answer:

Similarly, a method marked as async must have at least one await. On an await, the runtime will save the current thread's state and call stack, make the asynchronous call, and unwind back to the runtime's message loop to handle the next message and keep the app responsive. When the asynchronous operation is complete, at the next scheduling opportunity, the call stack to up the async operation is pushed back in and continued as if the call was synchronous.

But from msdn:

If the method does not contain an await expression or statement, then it executes synchronously. A compiler warning alerts you to any async methods that don't contain await because that situation might indicate an error.

What type of error occur that merits this being a compiler warning versus just recommended usage?

Community
  • 1
  • 1
xdumaine
  • 10,096
  • 6
  • 62
  • 103

1 Answers1

6

MSDN has a good description for this warning: Compiler Warning (level 1) CS4014. The good quote from it will be:

In most cases, that behavior isn't what you expect.

I think that the main reason why this warning exists is that async/await is not really obvious, and developers usually do mistakes like I will describe below.

For example you have a method, which do something heavy for several seconds:

public int DoSomething()
{
    int sum = 0;

    for (int i = 0; i < 10; i++)
    {
        sum += i;
        Thread.Sleep(1000);
    }

    return sum;
}

You heard about async and await somewhere and you want to try them. And this is how very often people think that they will move everything to background (maybe not often, but I thought that this is how it works before I read more documentation, so we can count at least me):

public async Task<int> DoSomething()
{
    int sum = 0;

    for (int i = 0; i < 10; i++)
    {
        sum += i;
        Thread.Sleep(1000);
    }

    return sum;
}

You think that problem is solved, but warning tells you that without await you should not use async, because it just does nothing, all your code will run synchronously, the last sample with async is similar to next code:

public Task<int> DoSomething()
{
    int sum = 0;

    for (int i = 0; i < 10; i++)
    {
        sum += i;
        Thread.Sleep(1000);
    }

    return Task.Result<int>(sum);
}

Where you do everything on the same context, which calls this method.

So the main reason of this warning I think to let people know that probably they use async wrong and this is a time to read documentation.

outcoldman
  • 11,584
  • 2
  • 26
  • 30