In existing rule csharpsquid:S3168 (“async” methods should not return “void”) there is a problem with proposed Compliant solution.
Current Compliant solution:
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;
}
}
The problem is with public void Method()
. The operator await
is used inside, but method is not marked with async
modifier. This will result in following compilation error:
error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
Proposed solution (new version of Compliant solution):
private async Task ThrowExceptionAsync() // Compliant: async method return type is 'Task'
{
throw new InvalidOperationException();
}
public void Method() => _ = Task.Run(async () =>
{
try
{
await ThrowExceptionAsync();
}
catch (Exception)
{
// The exception is caught here
throw;
}
});