简体   繁体   English

Async / Await没有等待呼叫

[英]Async/Await without await call

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 ? IDE确实给了我警告,处理这个问题的正确方法是什么?

In my base class: 在我的基类:

protected virtual async Task GoNext ()

From the base class it get called via await. 从基类开始,它通过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. 然后在我的子类中,我重写了这个方法,但有时候它确实包含了await和它没有的时间。

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. async关键字实际上不是继承方法签名的一部分,而是更多的编译器信号,它需要根据异步方法的模式编译和重写方法。

As such, you can leave out the async keyword on inherited methods if the inherited method does not use the await keyword. 因此,如果继承的方法不使用await关键字,则可以在继承的方法上省略async关键字。

Note that you will still have to return a Task or Task<T> , that part is part of the inherited method signature. 请注意,您仍然必须返回TaskTask<T> ,该部分继承方法签名的一部分。

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

The warning is this: 警告是这样的:

Warning: CS1998 This async method lacks 'await' operators and will run synchronously. 警告:CS1998此异步方法缺少'await'运算符并将同步运行。 Consider using the await operator to await non-blocking API calls, or await Task.Run(...) to do CPU-bound work on a background thread. 考虑使用await运算符等待非阻塞API调用,或者await Task.Run(...)在后台线程上执行CPU绑定工作。

This, however, will not produce a warning: 但是,这不会产生警告:

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

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> . 请注意,我在最后一个方法中更改了return语句,因为async关键字带来的“魔法”部分是自动将返回值包装在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. 如果你有其他方法可以获得Task<T> ,显然你不需要像上面那样包装结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM