Fix MA0004 using the ConfigureAwait of nested functions to detect the context

Merged
ME
2mo ago
+45-5

What

In a context that has a SynchronizationContext (WPF, WinForms, Blazor, ...), MA0004 reports a missing ConfigureAwait only after a previous ConfigureAwait(false) in the same method. The previous awaits were collected from the whole MethodDeclarationSyntax, including the nested lambdas and local functions, so a ConfigureAwait(false) inside a lambda changed the reporting of the enclosing method:

class MyClass : System.Windows.Window
{
    async Task Test()
    {
        Func<Task> f = async () => await Task.Delay(1).ConfigureAwait(false);
        await Task.Delay(1);
    }
}

The await of Test runs on the UI thread whatever the lambda does. The same issue happened in the other direction: a ConfigureAwait(false) in the method made the awaits of a lambda declared after it reported, whereas the lambda runs in the context of its caller.

Fix

HasPreviousConfigureAwait only considers the configured awaits whose containing function (lambda, anonymous method, local function, or method) is the same as the one of the analyzed await.

The existing test AfterConfigureAwaitFalse_InLambda_InWpfWindowClass_ShouldReportError encoded the second direction (a ConfigureAwait(false) in the method made the await of a lambda reported). It is renamed to AfterConfigureAwaitFalse_InLambda_InWpfWindowClass_ShouldNotReportError and now expects no diagnostic: the lambda is not a continuation of the method, so the ConfigureAwait(false) of the method says nothing about the context the lambda runs in. This test was added by #1402 to characterize the behavior at the time, not as a requirement.

Tests

  • Added AfterConfigureAwaitFalse_InNestedLambda_InWpfWindowClass_ShouldNotReportError and AfterConfigureAwaitFalse_InNestedLocalFunction_InWpfWindowClass_ShouldNotReportError (both failed before the fix).
  • Updated AfterConfigureAwaitFalse_InLambda_InWpfWindowClass_ShouldNotReportError (see above).

UseConfigureAwaitAnalyzerTests passes on roslyn5.9 (43/43) and roslyn4.8 (43/43).

Note: two awaits in the same lambda body (await X.ConfigureAwait(false); await Y; in an async lambda of a WPF window) are still not reported, before and after this change. IsReachableFrom walks the enclosing statements up to the method body, past the lambda, which is the likely cause. This is left for a separate change.