英文:
How to get a warning on an unawaited task from non async code
问题
不会产生警告。这导致了我的代码中出现了一些未发现的错误,因为异常没有被观察到。
如果调用方法是异步的,我会收到警告,但希望在调用方法为非异步时也能收到相同的警告。
我明白你不能从非异步方法中等待,修复方法是将调用方法设为异步,然后等待它。但我希望得到一条警告,让我知道我应该这样做。
在这种情况下,是否有办法让C#编译器生成一个警告?
英文:
If I forget to await a Task returned from an async method from in non async method I don't get a warning. This has resulted in several undiscovered bugs in my code due to unobserved exceptions.
I do get a warning if the calling method is async, but would like the same thing for when the calling method is non async.
I understand that you can't await from a non async method, the fix is to make the calling method async and then await it. But I would like a warning letting me know I should do this.
Is there a way to get the c# compiler to generate a warning in this case?
答案1
得分: 5
Microsoft.VisualStudio.Threading Roslyn分析器针对以下情况生成警告:
https://www.nuget.org/packages/Microsoft.VisualStudio.Threading.Analyzers
它生成以下警告:
警告 VSTHRD110:通过等待它、分配给变量或将其传递给另一个方法来观察此方法调用的可等待结果
您可以通过添加以下内容将其包含在您的项目中:
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.5.22">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
如果使用vs4mac,您可能需要清理并重新构建以使警告开始工作。
英文:
The Mirosoft.VisualStudio.Threading roslyn analyzer produces warnings for these cases:
https://www.nuget.org/packages/Microsoft.VisualStudio.Threading.Analyzers
It produces the following warning:
> warning VSTHRD110: Observe the awaitable result of this method call by awaiting it, assigning to a variable, or passing it to another
> method
This can be included in your project by adding the following:
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.5.22">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
If using vs4mac you may need to clean and rebuild to get the warning to start working.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论