async await return Task

David Dury picture David Dury · Aug 7, 2014 · Viewed 230.9k times · Source

Can somebody explain what does this means into a synchronous method? If I try to change the method to async then VS complain about it.

This works:

public Task MethodName()
{
     return Task.FromResult<object>(null);
}

This doesn't work:

public async Task MethodName()
{
     return Task.FromResult<object>(null);
}

So basically I would like to know what exactly this means: Task.FromResult<object>(null);

Answer

Sriram Sakthivel picture Sriram Sakthivel · Aug 7, 2014

async methods are different than normal methods. Whatever you return from async methods are wrapped in a Task.

If you return no value(void) it will be wrapped in Task, If you return int it will be wrapped in Task<int> and so on.

If your async method needs to return int you'd mark the return type of the method as Task<int> and you'll return plain int not the Task<int>. Compiler will convert the int to Task<int> for you.

private async Task<int> MethodName()
{
    await SomethingAsync();
    return 42;//Note we return int not Task<int> and that compiles
}

Sameway, When you return Task<object> your method's return type should be Task<Task<object>>

public async Task<Task<object>> MethodName()
{
     return Task.FromResult<object>(null);//This will compile
}

Since your method is returning Task, it shouldn't return any value. Otherwise it won't compile.

public async Task MethodName()
{
     return;//This should work but return is redundant and also method is useless.
}

Keep in mind that async method without an await statement is not async.