Tiber Septim
Tiber Septim

Reputation: 335

Keep Task and Task.FromResult if method is synchronous or remove Task-stuff at all?

I have a Web API controller (ASP.NET Core 5). Some of my APIs are asynchronous and some of them not. My question is next: Is there any advantages of using public **Task<T>** WebApiMethod + Task.FromResult() in Web API controllers if my method is synchronous?

For example:

public Task<string> GetSomeData()
{
    // some synchronous processing...
    return Task.FromResult(result);
}

Should I turn the example code above to something like this?

public string GetSomeData()
{
    // some synchronous processing...
    return result;
}

Upvotes: 4

Views: 432

Answers (3)

Ran Turner
Ran Turner

Reputation: 18036

If the api is doing synchronous work it should have a synchronous signature. it will make the readability and understanding of the function clearer to other developers and will prevent misunderstanding when reading this function again in the future.

In the future, if the method will need to be modified to have an asynchronous task to do, you can change the signature to have an asynchronous signature.

Upvotes: 5

phimath
phimath

Reputation: 151

You should use synchronous methods if the work is synchronous.

Yet, you should use Task signatures if you use some form of caching (e.g. with the proxy pattern). Then, of course if you already did the expensive I/O work, use Task.FromResult to return the cached result, and return the I/O task if it has to be newly downloaded.

Upvotes: 1

Pramod Narayan
Pramod Narayan

Reputation: 47

It shouldn't have much difference in the way it is executed. If you can make the processing part asynchronous then it would make some difference.

Upvotes: 0

Related Questions