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?

4

1 回答 1

6

MSDN 对此警告有很好的描述:Compiler Warning (level 1) CS4014。好的报价将是:

在大多数情况下,这种行为不是您所期望的。

我认为这个警告存在的主要原因是 async/await 不是很明显,开发人员通常会犯我将在下面描述的错误。

例如,您有一个方法,它会在几秒钟内执行一些繁重的操作:

public int DoSomething()
{
    int sum = 0;

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

    return sum;
}

您听说过async并且await想尝试一下。这就是人们经常认为他们会将所有内容移至后台的频率(可能并不经常,但我认为在我阅读更多文档之前它就是这样工作的,所以我们至少可以数我):

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

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

    return sum;
}

您认为问题已解决,但警告告诉您,没有await您不应该使用async,因为它什么也不做,您的所有代码都将同步运行,最后一个示例async类似于下一个代码:

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

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

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

您在同一个上下文中执行所有操作,这会调用此方法。

所以我认为这个警告的主要原因是让人们知道他们可能用async错了,现在是阅读文档的时候了。

于 2013-04-11T05:13:17.040 回答