Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous and synchronous methods [duplicate]

Tags:

c#

async-await

I have an asynchronous method:

public async Task<Foo> GetFooAsync();

And I need its synchronous version. Something like this:

public Foo GetFoo();

I do not really want to totally rewrite code of GetFooAsync and I would like to do something such as

public Foo GetFoo() 
{
    return GetFooAsync().GetAwaiter().GetResult();
}

Is it good idea or this method has any unobvious problems? As I know if I use GetFooAsync().Result in synchronous context I may face with deadlock. But what about GetFooAsync().GetAwaiter().GetResult()?

like image 820
Pupkin Avatar asked Dec 31 '25 15:12

Pupkin


1 Answers

Mixing synchronous/async code may lead to deadlocks as described in this article (paragraph 'Async all the way').

Problem is where Task continuation runs and that depends on current SynchronizationContext. If the synchronization is meant to be scheduled on the same thread that's currently blocked by call to Wait()/Result/GetResult() you're running into trouble

like image 135
orhtej2 Avatar answered Jan 03 '26 05:01

orhtej2



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!