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
TaskorValueTask, 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.BeginInvokeorDispatcher.Invoketo run the asynchronous code without blocking the event handler. - Remove
asyncand make sure the method executes in aTask.Runconstruct. 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
}async void OnWebResponse(object sender, NetworkEventArgs e) // CSL1015: Avoid async void: method 'OnWebResponse' should return Task
{
}