c# – 为什么在ConfigureAwait之后保留文化(false)

前端之家收集整理的这篇文章主要介绍了c# – 为什么在ConfigureAwait之后保留文化(false)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下异步代码
// Main system culture is English here
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("es");

WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Culture:{Thread.CurrentThread.CurrentCulture}");

await Task.Delay(1).ConfigureAwait(false);

WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Culture:{Thread.CurrentThread.CurrentCulture}");

我期望的结果是在等待之后具有不同的线程id并且新的线程id再次具有未修改的系统文化.

这没有发生;线程确实与前一个不同,但文化以某种方式从前一个线程流出.

如果我建议使用ConfigureAwait,我不需要保留SynchronisationContext,为什么要保持文化?我的理解是文化没有存储在ExecutionContext上,因此我不确定为什么会这样.

这是一个控制台应用程序.

完整示例代码https://pastebin.com/raw/rE6vZ9Jm

解决方法

这是.NET 4.6的预期行为.

Julien无法重现它的原因是他可能针对框架的较低版本(例如,在4.5.2中,文化不会流动).

关于这个主题Here is the official documentation.

具体请注意以下几点:

… starting with apps that target the .NET Framework 4.6,asynchronous operations by default inherit the values of the CurrentCulture and CurrentUICulture properties of the thread from which they are launched. If the current culture or current UI culture differs from the system culture,the current culture crosses thread boundaries and becomes the current culture of the thread pool thread that is executing an asynchronous operation.

原文链接:https://www.f2er.com/csharp/92337.html

猜你在找的C#相关文章