Water Cooler v2 Water Cooler v2 - 2 years ago 109
C# Question

ConfigureAwait(false) when using ContinueWith

What's the equivalent of using:

await task.ConfigureAwait(false);

when using continuations like so (without using the C# compiler's

var taskOfString = ScheduleWorkOnThreadPoolAsync();

// I'd like this continuation to not have to
// "flow" the synchronization context but to simply
// execute wherever it can, i.e. I'd like to tell is
// ConfigureAwait(false) for its previous task.
// How do I do that?
taskOfString.ContinueWith(t => { });

public async Task<string> ScheduleWorkOnThreadPoolAsync()
return Task.Run(() => return "Foo" );

I am assuming that doing nothing, i.e. just leaving it as is is equivalent to calling
, which is also what I see happening when I debug the code. It hops on whatever thread it can.

It is only when we want to specify a scheduler or synchronization context to run the continuation on that we need to pass in extra information to the overload that accepts a
. Otherwise, it is defaulted to run without any regard to the execution context.

However, I still request a confirmation or correction if I am wrong.

Answer Source

I've looked into the reference source of Task then ConfiguredTaskAwaitable via GetAwaiter.OnCompleted back through into Task.SetContinuationForAwait (with continueOnCapturedContext as false), and it drops into:

if (!AddTaskContinuation(tc, addBeforeOthers: false))
        tc.Run(this, bCanInlineContinuationTask: false);

which is, basically, ContinueWith. So: yes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download