为什么 async await 调用后 Thread.CurrentPrincipal 不持久

Why is Thread.CurrentPrincipal not persisting after async await call

提问人:David Klempfner 提问时间:10/16/2023 最后编辑:David Klempfner 更新时间:10/17/2023 访问量:36

问:

我有以下代码:

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;
}

我设置为 ,然后如果我调用 ,则该值随后会保留。Thread.CurrentPrincipalnew CustomPrincipal("A")await Task.Delay(1000).ConfigureAwait(false)

但是,如果我调用 ,则该值不会持久化,并且仍包含其原始值。Task.Delay(1000)Thread.CurrentPrincipal

这似乎与基于此答案应该发生的情况相反:

ASP.NET 使用其 SynchronizationContext 设置 Thread.CurrentPrincipal。

我以为如果你使用,原来的上下文不会放回去,我以为会包含原来的..ConfigureAwait(false)Thread.CurrentPrincipal

是否链接到同步上下文?如果是这样,为什么当我返回到原始上下文时,我为其设置的值没有保留?Thread.CurrentPrincipal

更新:

我有,并在web.config中设置。<httpRuntime targetFramework="4.5" requestValidationMode="4.5" enableVersionHeader="false" /><compilation targetFramework="4.5.2" debug="true">

但是,在 .csproj 中设置。<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>

asp.net 异步 async-await net-4.7.2 synchronizationcontext

评论

1赞 D A 10/16/2023
我认为您在提供的“答案”链接中拥有所有答案。从那里阅读所有答案。我认为关于“SynchronizationContext”最相关的解释是“当方法完成时,执行上下文将返回到其以前的状态”。
0赞 Stephen Cleary 10/16/2023
你的设置是什么?httpRuntime.targetFramework
0赞 David Klempfner 10/17/2023
@StephenCleary 4.5.我觉得这很奇怪,因为它在我的 .csproj 文件中。<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>

答: 暂无答案