Water Cooler v2 Water Cooler v2 - 1 year ago 90
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
async/await
transformations)?

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
ConfigureAwait(false)
, 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
TaskScheduler
. 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