An async method with a
void return type does not follow the task asynchronous programming
(TAP) model since the return type should be Task or Task<TResult>
Doing so prevents control over the asynchronous execution, such as:
EventHandler delegate signature. Using void for EventHandler is compliant with the TAP model.
public async void button1_Click(object sender, EventArgs e)
{
await DoSomethingAsync();
}
On[A-Z]\w* pattern. Some frameworks may not use the same EventHandler method signature
public async void OnClick(EventContext data)
{
await DoSomethingAsync();
}
Update the return type of the method from void to Task.
private async void ThrowExceptionAsync() // Noncompliant: async method return type is 'void'
{
throw new InvalidOperationException();
}
public void Method()
{
try
{
ThrowExceptionAsync();
}
catch (Exception)
{
// The exception is never caught here
throw;
}
}
private async Task ThrowExceptionAsync() // Compliant: async method return type is 'Task'
{
throw new InvalidOperationException();
}
public void Method()
{
try
{
await ThrowExceptionAsync();
}
catch (Exception)
{
// The exception is caught here
throw;
}
}
async (C#
Reference) Task Class Task<TResult>
Class EventHandler Delegate