Suppress warning from empty async method

before .Net 4.6 we had to return a dummy value which we do not need. However, now we can do it like this:

public async Task MyFunctionAsync()
{
    // Some work here...
    await Task.CompletedTask;
}

Or of course, yet better, remove the async and await keywords from the code here, because async is not part of the the interface contract:

public Task MyFunctionAsync()
{
    // Some work here...
    Task.CompletedTask;
}

This way will prevent the compiler warning instead of muting it:

For anybody interested, if you ever need to circumvent such a compiler warning:

public async Task DoStuff
{
    // This method should stay empty
    // Following statement will prevent a compiler warning:
    await Task.FromResult(0);
}

This is a somewhat common problem when you have a synchronous (or noop) implementation for an asynchronous interface.

You can implement a Task-returning method without the async keyword by just returning a completed Task, as such:

public Task FinalizeAsync()
{
  return Task.FromResult(0);
}

However, this still allocates a Task every time it's called. If you find yourself doing this a lot, you may want to cache a completed Task instance. My AsyncEx library provides a number of task constants for this purpose:

public Task FinalizeAsync()
{
  return TaskConstants.Completed;
}

Finally, you may want to take a look at my blog post on asynchronous disposal for a couple of alternative approaches.


You can put the following directive on the file(s):

#pragma warning disable 1998

However, I'd recommend leaving the warning alone, and taking its advice. It's a warning for a good reason ;)

EDIT: if you want to disable the warning for just one method, you can do this:

#pragma warning disable 1998
async Task Foo() {}
#pragma warning restore 1998