我有以下异步代码:
// 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上,因此我不确定为什么会这样.
这是一个控制台应用程序.
解决方法
这是.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.