Suppress warning from empty async method

2019-04-03 06:27发布

Let's just go ahead and say I have the following function:

public class Test
{
    public async Task Finalize()
    {
        // We don't need this in this class, so empty body
    }

    /*
     * Additional methods snipped
     */
}

While this works just fine, I will get a compiler warning saying:

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

What would be the best way to circumvent this warning without modifying the method too much? In this case, I'm not able to throw an exception, since the method will get called, but absolutely nothing is bound to happen at this point, since the class I'm talking about has nothing to finalize.

5条回答
家丑人穷心不美
2楼-- · 2019-04-03 06:38

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
查看更多
贪生不怕死
3楼-- · 2019-04-03 06:38

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.

查看更多
再贱就再见
4楼-- · 2019-04-03 06:41

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);
}
查看更多
干净又极端
5楼-- · 2019-04-03 06:43

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 works here...
    await Task.CompletedTask;
}
查看更多
来,给爷笑一个
6楼-- · 2019-04-03 06:50

Remove "async" and the warning goes away:

public class Test
{
    public void Finalize()
    {
        // We don't need this in this class, so empty body
    }
 }
查看更多
登录 后发表回答