简体   繁体   English

如何在返回Task的方法中调用异步方法?

[英]How to call async method in a method that returns Task?

In the SignalR hub I've this: 在SignalR中心我是这样的:

public class MyHub : Hub
{
    public override Task OnConnected()
    {
        // my async code here
        return base.OnConnected();
    }
}

I want to perform an async code. 我想执行异步代码。 So I added async keyword like this: 所以我添加了async关键字,如下所示:

public class MyHub : Hub
{
    public override async Task OnConnected()
    {
        var result = await MyAsyncMethod();
        return base.OnConnected();
    }
}

but return base.OnConnected(); 但是return base.OnConnected(); shows this error: 显示此错误:

Since MyHub.OnConnected() is an async method that returns Task , a returned keyword must not be followed by an object expression. 由于MyHub.OnConnected()是一个返回Task的异步方法,因此返回的关键字后面不能跟一个对象表达式。 Did you intend to return Task<T> ? 你打算返回Task<T>吗?

How can I fix it? 我该如何解决? thanks. 谢谢。

An async method is converted into a state machine by the compiler. 编译器将async方法转换为状态机。 You cannot return that Task here, because the Task returned is generated by the compiler and represents the continuation of this method. 您无法在此处returnTask ,因为返回的Task是由编译器生成的,并表示此方法的延续

Simply await the base call: 只需await base呼叫:

public override async Task OnConnected()
{
    var result = await MyAsyncMethod();
    await base.OnConnected();
}

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

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