How should Roslyn Analyzer actions handle async code?

Viewed 586

I have a Roslyn analyzer which I've recently updated to use version 2.3 of CSharp.Workspaces. I found that when I build I get a warning like the following:

Analyzer attempted to register an 'async' action, which is not supported.

Some of the actions I'm adding are async because they are calling async methods from the Roslyn API, like in the following hypothetical example.

public override void Initialize(AnalysisContext context)
{
    context.RegisterSymbolAction(AnalyzeProperty, SymbolKind.Property);
}

private async void AnalyzeProperty(SymbolAnalysisContext context)
{
    var property = (IPropertySymbol) context.Symbol;
    foreach (var syntaxRef in property.DeclaringSyntaxReferences)
    {
        DoSomethingWith(await syntaxRef.GetSyntaxAsync());
    }
}

Should I just change any uses of await to .Result or .Wait() on the Task, or is there some other way I should correct my code in response to the warning?

1 Answers

you shouldn't use await in synchronous context. that will cause timing issue that is hard to debug.

use synchronous version of the API. http://sourceroslyn.io/#Microsoft.CodeAnalysis/Syntax/SyntaxReference.cs,29

by the way, using async API with Wait() or Result might not as bad as using await in synchronous context, but it could be still bad since that might cause thread starvation since you are blocking current thread just to wait another thread to finish work and return.

best way is using synchronous API in synchronous context. and async API in asynchronous context.

Related