异步/等待,无需等待呼叫 [英] Async/Await without await call

查看:107
本文介绍了异步/等待,无需等待呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个虚拟方法,该方法有时包含await调用,有时不包含.IDE确实会警告我,正确的处理方式是什么?

I have a virtual method that sometimes contain await calls and sometimes doesn't. The IDE does give me warning, what is the proper way of handling this ?

在我的基类中:

protected virtual async Task GoNext ()

从基类开始,它通过等待被调用.

From the base class it get called via await.

然后在我的子类中,我重写了此方法,但有时它确实包含等待,而有时不包含.

Then in my sub-classes i override this method but there are times that it does include a await and times that it doesn't.

推荐答案

async 关键字实际上不是继承的方法签名的一部分,而是更多向编译器发出的信号,它需要进行编译并根据异步方法的模式重写该方法.

The async keyword is not actually part of the inherited method signature, but more of a signal to the compiler that it needs to compile and rewrite the method according to the pattern for async methods.

这样,如果继承的方法不使用 await 关键字,则可以在继承的方法上省略 async 关键字.

As such, you can leave out the async keyword on inherited methods if the inherited method does not use the await keyword.

请注意,您仍然必须返回 Task Task< T> ,这部分是继承的方法签名的一部分.

Note that you will still have to return a Task or Task<T>, that part is part of the inherited method signature.

因此,这会给您一个警告:

So this will give you a warning:

class Base
{
    public virtual async Task<int> Method()
    {
        await Task.Delay(10);
        return 42;
    }
}

class Derived : Base
{
    // next line produces warning
    public override async Task<int> Method()
    {
        return 42;
    }
}

警告是这样

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

Warning: CS1998 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.

但是,这不会产生警告:

This, however, will not produce a warning:

class Derived : Base
{
    public override Task<int> Method()
    {
        return Task.FromResult(42);
    }
}

请注意,我在最后一个方法中更改了 return 语句,因为 async 关键字带来的魔术"的一部分是将返回值自动包装在 Task< T> .如果您还有其他获取 Task< T> 的方法,显然您不需要像我上面那样包装结果.

Note that I changed the return statement in that last method because part of the "magic" that the async keyword brings is to automatically wrap the return value inside a Task<T>. If you have other ways of obtaining a Task<T>, obviously you do not need to wrap the result like I did above.

这篇关于异步/等待,无需等待呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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