为什么在ConfigureAwait(false)之后保留区域性 [英] Why is the culture kept after ConfigureAwait(false)

查看:80
本文介绍了为什么在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仍具有未修改的系统文化.

The resul I expected would be to have a different thread id after the await and that new thread id having the unmodified system culture again.

这没有发生;该线程确实与以前的线程有所不同,但是文化在某种程度上源于先前的线程.

This is not happening; the thread is indeed different from the previous, but the culture is somehow flowing from the previous thread.

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

Why is it keeping the culture if I suggested with ConfigureAwait that I don't need to keep the SynchronisationContext? It is my understanding that the culture is not stored on the ExecutionContext therefore I am not sure why this is happening.

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

This is a Console application.

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

推荐答案

从.NET 4.6开始,这是预期的行为.

This is expected behaviour as of .NET 4.6.

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

The reason Julien could not reproduce it is that he's likely targeting a lower version of the framework (in 4.5.2, for instance, culture doesn't flow).

此处为官方文档.

特别注意以下几点:

...从面向.NET Framework 4.6的应用程序开始,异步操作默认情况下会继承从中启动它们的线程的CurrentCulture和CurrentUICulture属性的值.如果当前区域性或当前UI区域性与系统区域性不同,则当前区域性会跨越线程边界,并成为执行异步操作的线程池线程的当前区域性.

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

这篇关于为什么在ConfigureAwait(false)之后保留区域性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆