I recently saw this in code:
await QueryAsync.ConfigureAwait(SynchronizationContext.Current is not null || TaskScheduler.Current != TaskScheduler.Default)
My first thought was, "that's not right", but is it?
My understanding is that if there is no current synchronization context, we should use .ConfigureAwait(false). If there IS a current synchronization context, we MIGHT (note the UPPER-CASE 'MIGHT') need to use .ConfigureAwait(true), which is basically the same as not using .ConfigureAwait at all.
If my understanding is correct (which it likely is not), that code would work and could be put into an extension for even more brevity.
Am I incorrect?
I have tried testing this and it seems to work in that .ConfigureAwait(true) is called when there is a synchronization context, and .ConfigureAwait(false) when SynchronizationContext.Current is null.
Edit: To clarify, if there is no current SynchronizationContext AND no custom TaskScheduler, this code evaluates to:
await QueryAsync().ConfigureAwait(false);
When there IS a current SynchronizationContext, or a custom TaskScheduler, it evaluates to:
await QueryAsync().ConfigureAwait(true);
which, according to to this article, is basically the same as:
await QueryAsync();
The code in the question:
await QueryAsync().ConfigureAwait(SynchronizationContext.Current is not null ||
TaskScheduler.Current != TaskScheduler.Default);
...is equivalent to this:
await QueryAsync();
The .ConfigureAwait(true)
is the default, so it can be omitted. In case there is no synchronization context to capture at the await
point, both .ConfigureAwait(true)
and .ConfigureAwait(false)
behave the same.
In other words, this piece of sophisticated code is a whole lot of nothing.