Report MA0147 on async void method groups

Merged
ME
2mo ago
+72-1

What

MA0147 (Avoid async void method for delegate) only matched IAnonymousFunctionOperation, so it reported the lambda form but said nothing about an async void method group converted to a void-returning delegate:

class Sample
{
    async void Handler() => await Task.Delay(1);

    void M()
    {
        Action a1 = async () => await Task.Delay(1);  // MA0147 reported
        Action a2 = Handler;                          // no diagnostic (before this change)
    }
}

The target check in DoNotUseAsyncDelegateForSyncDelegateAnalyzer is now a switch that also matches IMethodReferenceOperation when the referenced method is both async and void-returning:

var isAsyncVoid = operation.Target switch
{
    IAnonymousFunctionOperation { Symbol.IsAsync: true } => true,
    IMethodReferenceOperation { Method: { IsAsync: true, ReturnsVoid: true } } => true,
    _ => false,
};

Why

Both forms have the same problem: the exception is lost and the caller cannot observe completion. The method-group form was a false negative.

Notes for the reviewer

  • The ReturnsVoid check on the method reference is what keeps async Task method groups quiet. The enclosing DelegateInvokeMethod.ReturnsVoid guard alone is about the delegate type, not the target's own return type.
  • The existing operation.Parent is IEventAssignmentOperation exclusion already covers the legitimate someEvent += Handler; case for method groups too; there is a new test asserting that.
  • This widens the rule for existing users. Non-event callback registrations that intentionally pass an async void method group (a fire-and-forget timer or message-pump callback, say) will now warn where they did not before. That is the intended behavior of the rule, just newly reachable.

Tests

Four tests added to DoNotUseAsyncDelegateForSyncDelegateAnalyzerTests:

  • Action_AsyncVoidMethodGroup — reports (the new coverage)
  • Action_SyncMethodGroup — no diagnostic
  • FuncTask_AsyncMethodGroup — no diagnostic, guards against flagging async Task method groups
  • Event_AsyncVoidMethodGroup — no diagnostic

All five Roslyn versions pass (14 tests each: 4.8, 4.14, 5.0, 5.6, 5.9). dotnet run --project src/DocumentationGenerator exits 0 with no further markdown changes.

docs/Rules/MA0147.md gains the method-group non-compliant example.