Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call async method in a method that returns Task?

In the SignalR hub I've this:

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:

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

but 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. Did you intend to return Task<T>?

How can I fix it? thanks.

like image 336
Blendester Avatar asked Dec 19 '22 04:12

Blendester


1 Answers

An async method is converted into a state machine by the compiler. You cannot return that Task here, because the Task returned is generated by the compiler and represents the continuation of this method.

Simply await the base call:

public override async Task OnConnected()
{
    var result = await MyAsyncMethod();
    await base.OnConnected();
}
like image 53
René Vogt Avatar answered Jan 06 '23 12:01

René Vogt