Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it useful to mark a method async when it only awaits at the return statement? [duplicate]

Tags:

c#

async-await

Only the last line of the method below is using 'await', just before the method returns, so doesn't this mean that method is basically synchronous and should just be called "Get()" without the async modifier and the suffix Async?

public virtual async Task<TEntity> GetAsync(Guid id)
{
    // some more code here
    return await _dbSet.FindAsync(id);
}
like image 808
epitka Avatar asked Jan 25 '17 15:01

epitka


1 Answers

doesn't this mean that method is basically synchronous

No. It's asynchronous. You're probably thinking of sequential (progressing from one thing to the next), not synchronous (blocking the current thread). An await will pause the method (sequentially) but not block the thread (asynchronously). For more information, see my async intro.

without the async modifier

While you could elide the async/await keywords, I would recommend that you do not. This is because // some more code here may throw an exception. I cover this and other considerations in my blog post on eliding async and await.

and the suffix Async?

No, that suffix is appropriate for any method that returns an awaitable (e.g., Task). So, even if you elide the async and await, it's still returning a task that should be awaited, so it should still have the Async suffix.

You can think of it this way: the Async suffix is part of the API interface. The async keyword is an implementation detail. They often go together, but not always.

like image 182
Stephen Cleary Avatar answered Sep 22 '22 07:09

Stephen Cleary