Skip to content

Latest commit

 

History

History
45 lines (36 loc) · 1.59 KB

File metadata and controls

45 lines (36 loc) · 1.59 KB

CSL1015: Do not declare async void methods

Methods returning void and marked async are valid C# code, but they should be avoided except for event handlers.

This is because if an exception occurs in the method, it cannot be caught by the caller. This can lead to unhandled exceptions and application crashes.

In the case of event handlers, you can use one of the following approaches:

  • Use the [AsyncEventHandler] attribute to indicate that the method is an asynchronous event handler. For more information, see the documentation for the AsyncEventHandler attribute.
  • Change the return type to Task or ValueTask, and update the event subscription accordingly. This is only possible if you can change the event delegate type.
  • If the event is defined in the WPF framework, use Dispatcher.BeginInvoke or Dispatcher.Invoke to run the asynchronous code without blocking the event handler.
  • Remove async and make sure the method executes in a Task.Run construct. For example:
using System;
using System.Threading.Tasks;

void OnWebResponse(object sender, NetworkEventArgs e)
{
    _ = Task.Run(async () =>
    {
        try
        {
            await OnWebResponseAsync(sender, e).ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            // Handle all exceptions
        }
    });
}

async Task OnWebResponseAsync(object sender, NetworkEventArgs e)
{
    // Your async code here
}

Sample code

async void OnWebResponse(object sender, NetworkEventArgs e) // CSL1015: Avoid async void: method 'OnWebResponse' should return Task
{
}