0

This question already has an answer here:

In my understanding, if I await an async function, then the following code will be wrapped in a delegate and executed after the async function returns:

async bool Test()
{
    await byte[] arr = ReadAsync(....)

    // all following code will be wrapped into a delegate
    if (arr != null)
    {
        // Do something

        return true;
    }

    return false;
}

It sounds like equal to if I explicitly wrap following code in a ContinueWith:

async bool Test()
{
    bool res = await ReadAsync(...)
                    .ContinueWith(t => 
                    {
                        byte[] arr = t.Result;
                        if (arr != null)
                        {
                            // Do something
                            return true;
                        }
                        return false;
                    });
}

Are there any differences between these two implementations?


  • I wouldn't really say that this one a duplicate because there the poster also has an additional .Wait()in the .ContinueWith() example. This is the actual mayor difference as the answer explains. - bitbonk

1 답변


4

One mayor difference is that if the thread you call await from has a SynchronizationContext, await will schedule the continuation inside that SynchronizationContext by default. So after the await you will be back on the same thread as before. You can change that by using .ConfigureAwait(false).

With .ContinueWith() it is eaxactly the other way around, by default it will be scheduled on an aribitary (threadpool) thread unless you pass TaskScheduler.FromCurrentSynchronizationContext() to it.


  • Thanks. So besides those implementation detail difference, are there any performance impacts or practice suggestions which implementation should be used? - codewarrior
  • @codewarrior That isn't an "implementation detail difference", that's something you actually have to think about as a programmer, that can make the difference between working and non-working code (where either can be the non-working code). - user743382

Linked


Related

Latest