Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async method .Result vs Sync method

Do these two methods work the same way? Both of these block the main thread, don't they?

// 1. Use async method
public IEnumerable<Entity> AsyncMethod()
{
    return Context.Entities.ToListAsync().Result;
}

// 2. Use sync method
public IEnumerable<Entity> SyncMethod()
{
    return Context.Entities.ToList();
}
like image 652
Oleg Mishenkin Avatar asked Jun 19 '26 05:06

Oleg Mishenkin


1 Answers

For the specific APIs you mention, I do not know whether they are the same or not; an expert on those APIs should answer.

In general, if there is a synchronous API and an asynchronous API, is taking the result of the asynchronous API guaranteed to be the same as the synchronous API?

No. A synchronous API should, as part of its contract, guarantee that it produces either a result or an exception in a reasonable amount of time. Taking the Result of an asynchronous API is permitted to "deadlock".

That's because an asynchronous API is permitted to work by scheduling work to be done on the current thread in the future, and then running the continuation of the associated task after it is complete. By requiring the Result synchronously, you can get into a situation where work is scheduled to be run in the future on this thread, but this thread is now blocking until the work is done, and we have a single-threaded deadlock situation.

For more details about why this causes deadlock and how to prevent it, please refer to this article.

It is almost never the right thing to do to get the Result of a task. If you need the result of a task, await it.

like image 164
Eric Lippert Avatar answered Jun 20 '26 18:06

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!