Find non-awaited async method calls

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: (?<!await|task(.*))\s([_a-zA-Z0-9\.])*Async\( 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.enter image description here

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. enter image description here

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.


After quite some difficulties with this problem I decided to create an Analyzer with code fix to solve it.

The code is available here: https://github.com/ykoksen/unused-task-warning

It is also as a NuGet package that can be used as an analyzer for a project (when it is build): https://www.nuget.org/packages/Lindhart.Analyser.MissingAwaitWarning/#

Furthermore it is also available as a Visual Studio Extension (for 2017). However this only analyses currently open files, so I'd recommend using the NuGet package. The extension is available here (or search for it in Visual Studio): https://marketplace.visualstudio.com/items?itemName=Lindhart.missingAwaitWarning#overview

The code for the analyzer:

    public override void Initialize(AnalysisContext context)
    {
        context.RegisterSyntaxNodeAction(AnalyseSymbolNode, SyntaxKind.InvocationExpression);
    }

    private void AnalyseSymbolNode(SyntaxNodeAnalysisContext syntaxNodeAnalysisContext)
    {
        if (syntaxNodeAnalysisContext.Node is InvocationExpressionSyntax node)
        {
            if (syntaxNodeAnalysisContext
                    .SemanticModel
                    .GetSymbolInfo(node.Expression, syntaxNodeAnalysisContext.CancellationToken)
                    .Symbol is IMethodSymbol methodSymbol)
            {
                if (node.Parent is ExpressionStatementSyntax)
                {
                    // Only checks for the two most common awaitable types. In principle this should instead check all types that are awaitable
                    if (EqualsType(methodSymbol.ReturnType, typeof(Task), typeof(ConfiguredTaskAwaitable)))
                    {
                        var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), methodSymbol.ToDisplayString());

                        syntaxNodeAnalysisContext.ReportDiagnostic(diagnostic);
                    }
                }
            }
        }
    }

    /// <summary>
    /// Checks if the <paramref name="typeSymbol"/> is one of the types specified
    /// </summary>
    /// <param name="typeSymbol"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    /// <remarks>This method should probably be rewritten so it doesn't merely compare the names, but instead the actual type.</remarks>
    private static bool EqualsType(ITypeSymbol typeSymbol, params Type[] type)
    {
        var fullSymbolNameWithoutGeneric = $"{typeSymbol.ContainingNamespace.ToDisplayString()}.{typeSymbol.Name}";
        return type.Any(x => fullSymbolNameWithoutGeneric.Equals(x.FullName));
    }

In the end, we used roslyn to find all instances where a return value of Task or Task<> was ignored:

if (methodSymbol.ReturnType.Equals(syntaxNodeAnalysisContext.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Task).FullName)))
{
    // For all such symbols, produce a diagnostic.
    var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), methodSymbol.ToDisplayString());

    syntaxNodeAnalysisContext.ReportDiagnostic(diagnostic);
}
if (((INamedTypeSymbol) methodSymbol.ReturnType).IsGenericType && ((INamedTypeSymbol) methodSymbol.ReturnType).BaseType.Equals(syntaxNodeAnalysisContext.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Task).FullName)))
{
    // For all such symbols, produce a diagnostic.
    var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), methodSymbol.ToDisplayString());

    syntaxNodeAnalysisContext.ReportDiagnostic(diagnostic);
}

Tags:

C#

Async Await