Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is making long-running calls async this simple?

I've just, for a rough draft, converted a whole lot of data access methods to async using the following pattern, and it looks too simple to be good enough for later iterations. How safe is it, what is missing, and how should I be doing it?

The service that provides long-running calls:

private class UserService
{
    public IdentityUser GetById(int id)
    {
        ...
    }
}

private UserService _userService = new UserService();

The original synchronous method:

public IdentityUser GetById(int id)
{
    return _userService.GetById(id);
}

My fantastic new async method:

public async Task<IdentityUser> GetByIdAsync(int id)
{
    await Task.Run(() => _userService.GetById(id));
}
like image 921
ProfK Avatar asked Jan 20 '16 18:01

ProfK


People also ask

What is an asynchronous call?

An asynchronous method call is a method used in . NET programming that returns to the caller immediately before the completion of its processing and without blocking the calling thread.

Is Task run asynchronous?

In . NET, Task. Run is used to asynchronously execute CPU-bound code.

What happens when you call async method?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.


1 Answers

You should not make "fake async" methods like this:

public async Task<IdentityUser> GetByIdAsync(int id)
{
    await Task.Run(() => _userService.GetById(id));
}

The reason I call it "fake async" is because there is nothing intrinsically async about the operation. In this case, you should have only the synchronous method. If a caller wants to make it async by using Task.Run, he can do that.

When is something intrinsically async? When you make a request to a web service or a database, for example, between sending the request and receiving the response there is a waiting period - the request is an intrinsically async operation. To avoid blocking the calling thread, use async-await.

like image 170
Timothy Shields Avatar answered Oct 13 '22 20:10

Timothy Shields