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

标签 c# .net asynchronous async-await task-parallel-library

我有以下异步代码:

// 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

最佳答案

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

关于c# - 为什么在 ConfigureAwait(false) 之后保留文化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45530837/

相关文章:

c# - 如何使用 using 指令包装流读取器?

c# - 在没有 Foreach 循环的情况下更新列表的单列

c# - EF ctx.Object.Select 和 obj.Select 之间的区别

scala - Future的onComplete和flatMap有什么区别?

ios - Firebase 和 Swift : Asynchronous calls, 完成处理程序

c# - Java/C# 消息传递的 REST 架构的性能

c# - 当应用程序处于焦点状态时,如何捕获 WinForms 应用程序上的键?

c# - 在生成的 Word 文档中格式化单元格

c# - 如何确定 Control.Visible 是通过属性设置的还是值是继承的

javascript - 异步代码,它是如何工作的? promise 和回调