I have the following code:
public async Task Get()
{
// With .ConfigureAwait(false): "AspNetSynchronizationContext"
// Without .ConfigureAwait(false): "AspNetSynchronizationContext"
var synchContext = SynchronizationContext.Current.GetType().Name;
// With .ConfigureAwait(false): "[email protected]"
// Without .ConfigureAwait(false): "[email protected]"
var originalName = Thread.CurrentPrincipal.Identity.Name;
Thread.CurrentPrincipal = new CustomPrincipal("A");
// With .ConfigureAwait(false): "A"
// Without .ConfigureAwait(false): "A"
var name = Thread.CurrentPrincipal.Identity.Name;
await Task.Delay(1000).ConfigureAwait(false);
//await Task.Delay(1000);
// With .ConfigureAwait(false): null
// Without .ConfigureAwait(false): "AspNetSynchronizationContext"
var newSynchContext = SynchronizationContext.Current?.GetType().Name;
// With .ConfigureAwait(false): "A"
// Without .ConfigureAwait(false): "[email protected]"
var newName = Thread.CurrentPrincipal.Identity.Name;
}
I set Thread.CurrentPrincipal
to new CustomPrincipal("A")
, then if I call await Task.Delay(1000).ConfigureAwait(false)
, the value is persisted afterwards.
However, if I call Task.Delay(1000)
, the value is not persisted, and Thread.CurrentPrincipal
still contains its original value.
This seems like the opposite of what should happen based on this answer:
ASP.NET uses its SynchronizationContext to set Thread.CurrentPrincipal.
I thought if you use .ConfigureAwait(false)
, the original context is not put back, which I thought would have contained the original Thread.CurrentPrincipal
.
Is Thread.CurrentPrincipal
linked to the synchronization context? If so, why is the value that I set for it not persisted when I return to the original context?
Update:
I have <httpRuntime targetFramework="4.5" requestValidationMode="4.5" enableVersionHeader="false" />
, and <compilation targetFramework="4.5.2" debug="true">
set in web.config.
However, <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
is set in .csproj.