Blendester
Blendester

Reputation: 1653

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.

Upvotes: 4

Views: 1819

Answers (1)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

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

Upvotes: 11

Related Questions