csharpsquid:S3168 has improper Compliant solution proposed

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;
  }
});
1 Like

Hello @albanur,

Thank you for reporting this!
It is very much appreciated.

I fixed the error in the code example, it will be available in the next release.

Have a nice day!