gpt4 book ai didi

async-await - 为什么没有 await 的异步函数会导致编译器警告?

转载 作者:行者123 更新时间:2023-12-01 15:56:12 31 4
gpt4 key购买 nike

谁能解释为什么 c# 5 中的异步函数需要至少有 1 个等待?我找不到明确的理由/解释。

所谓必需,是指当异步函数内部没有任何 await 调用时编译器会发出警告,但不会抛出编译错误。

来自 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.

但是来自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.

发生什么类型的错误值得将其作为编译器警告而不是仅推荐使用?

最佳答案

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

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

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

例如,您有一个方法,它会在几秒钟内做一些繁重的事情:

public int DoSomething()
{
int sum = 0;

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

return sum;
}

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

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 错误,现在是阅读文档的时候了。

关于async-await - 为什么没有 await 的异步函数会导致编译器警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940329/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com