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

Why is the culture kept after 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}");

我期望的结果是在 await 之后有一个不同的线程 ID,并且新的线程 ID 再次具有未修改的系统文化。

这不会发生;这个跟帖确实和以前的不一样,但是文化还是从以前的跟帖里流出来的。

如果我 建议 ConfigureAwait 不需要保留 SynchronisationContext,为什么要保留文化?据我了解,文化并未存储在 ExecutionContext 上,因此我不确定为什么会这样。

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

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

对新的 VS2017 控制台项目的快速测试显示了这个输出(en-GB 是我的默认文化):

1:Culture:es
4:Culture:en-GB

这是你(和我)所期望的。也许其他东西正在独立设置文化?

这是 .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.