在解决方案中查找丢失的 await

Find missing await in solution

我的服务器代码中有很多异步方法,但我怀疑我的调用者没有等待。

有没有一种简单的方法可以扫描缺少 await 的调用代码?

public async Task DomeSomethingAsync() 
{
     var result = await GetResult();
     await StoreResult(result);
}

然后在某个地方我忘记使用 await;

public async Task SomeBuggyCode()
{
     await Initialize();
     DoSomethingAsync();  // DOH - Forgot await
}

我希望有一种聪明的方法来识别这些错误的调用。

这应该显示为编译器警告 CS4014,文本为:

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

the documentation

所以你需要做的就是编译代码。 VS 应该允许您从其错误列表导航到相关位置。

如果该方法甚至不包含一个 await,您可以检查输出 window。编译后你会发现 This async method lacks 'await' operators and will run synchronously ... 警告。双击该警告将带您进入相关方法。

找到它们的最简单方法就是编译代码。

任何具有 async 但内部没有 await 的函数都会导致 compiler warning CS4014,编译项目后查看警告列表,您将看到所有需要修复的函数。

是的,您会收到警告,但是如果您的应用无需等待这些功能即可运行,也许您不想等待它们,只需将生成的任务分配给一个变量即可关闭这些人告诉您的警告。

显然这由您决定。

如果缺少“await”是针对编译器认为是异步的方法,则会生成 CS4014 警告。

如果在通过接口或在外部库中调用异步方法时错过等待,将无法正常工作。

因此,值得安装这个 nuget 包: https://www.nuget.org/packages/Lindhart.Analyser.MissingAwaitWarning/

如果 returns 未等待任务的方法

,这将在任何情况下发出警告

我注意到上面的警告仍然会漏掉 await 缺失的地方,比如这一行:

var before = _repositoryBase.GetAsync(id).CloneJson();

如果您有所有异步方法都称为 XXXAsync 的命名约定,则以下正则表达式将有助于查找潜在的缺失等待:

^((?!(await|async)).)*Async\(

Missing async await text search

特例。答案仅适用于 JetBrains 的 Rider IDE。 您可以使用 InspectCode,并在不等待的情况下查找所有调用异步方法: