如何从非异步代码中获得有关未等待任务的警告

huangapple go评论76阅读模式
英文:

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:

&lt;PackageReference Include=&quot;Microsoft.VisualStudio.Threading.Analyzers&quot; Version=&quot;17.5.22&quot;&gt;
  &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;
  &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers&lt;/IncludeAssets&gt;
&lt;/PackageReference&gt;

If using vs4mac you may need to clean and rebuild to get the warning to start working.

huangapple
  • 本文由 发表于 2023年2月14日 08:07:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定