Find non-awaited async method calls

前端 未结 5 1436
无人及你
无人及你 2020-12-24 11:36

I\'ve just stumbled across a rather dangerous scenario while migrating an ASP.NET application to the async/await model.

The situation is that I made a method async:

5条回答
  •  悲哀的现实
    2020-12-24 12:34

    You have a few options:

    • This is the simplest "Caveman" solution use the built in VS search functionality (CTRL + SHIFT + F) search in Entire solution, also under Find Options click on the checkbox Use Regular expression and use this regex: (? It assumes you post fixed all your async method with the Async keyword and the method call is in one line. If it is not true then do not use it (or add the missing validations to the expression).
    • Use some 3rd party code analyzer tool, Nuget package. ReSharper is very popular and I believe it able to detect this problems or you can create your own rules.
    • My choice would be to use Roslyn (@Volker provided one solution). You can create your own rule set with code fix solutions (light bulb icon will show your code fix) so this is the best.
    • UPDATE: VS 2019 checks for this problem by default and gives warnings.

    How to use Roslyn:

    • You have to install .NET Compiler Platform SDK: from here
    • Use VS 2017 Version 15.2 (or higher)
    • Create a new project File -> New -> Project, under the Extensibility group select: Analyzer with Code Fix (Nuget + VSIX) You have to target .NET Framework 4.6.2 to create this project.

    You can copy paste the previous solution. Create

    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class AsyncAwaitAnalyzer : DiagnosticAnalyzer
    { ...
    }
    

    class with logic, to detect the issue. And create

    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AsyncAwaitCodeFixProvider)), Shared]
    public class AsyncAwaitCodeFixProvider : CodeFixProvider
    { ...
    }
    

    class to provide fixing suggestions (add await) to the problem.

    After a success build you will get your own .wsix package you can install it to your VS instance and after a VS restart is should start pick up the problems.

提交回复
热议问题