禁止从空异步方法发出警告 [英] Suppress warning from empty async method

查看:56
本文介绍了禁止从空异步方法发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们继续说我具有以下功能:

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:

此异步方法缺少等待"运算符,将同步运行.考虑使用"await"运算符来等待非阻塞API调用,或者使用"await Task.Run(...)"来在后台线程上执行CPU绑定的工作.

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.

推荐答案

您可以在文件上放置以下指令:

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 ;)

如果只想禁用一种方法的警告,则可以执行以下操作:

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

这篇关于禁止从空异步方法发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆