背景:
我有一个异步等待函数,它从外部源获取语言和区域设置参数,这将用于设置为 CurrentUICulture。
我的 Web 应用程序是使用 C# 在 .NET Core 3.1 中构建的
问题:
CurrentUICulture 仅在 Child 方法的上下文中设置,一旦超出此范围,CurrentUICulture 就不会反映更改的值。
我的困境:
我知道始终建议从主线程(而不是从子线程)设置 CurrentUICulture 的值,但我正在处理一个对 Thread.CurrentThread.CurrentUICulture 有太多依赖的现有代码,实际上很难让我在不同的地方改变。
片段:
public class Example
{
public static async Task Main()
{
Console.WriteLine("Main Thread: Current UI culture is {0}",
Thread.CurrentThread.CurrentUICulture.Name);
await Child();
Console.WriteLine("Main Thread: UI culture after change is {0}",
Thread.CurrentThread.CurrentUICulture.Name);
}
public static async Task Child()
{
//get the culture text from an external service (assume this will return "pt-BR")
var cultureText = await externalService.GetCultureAsync();
//set the culture
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureText);
Console.WriteLine("Child Thread: UI culture changed to {0}",
Thread.CurrentThread.CurrentUICulture.Name);
}
}
实际输出:
(假设外部服务返回的值为“pt-BR”[葡萄牙语巴西])
Main Thread: Current UI culture is en-US
Child Thread: UI culture changed to pt-BR
Main Thread: UI culture after change is en-US
期望的输出:
Main Thread: Current UI culture is en-US
Child Thread: UI culture changed to pt-BR
Main Thread: UI culture after change is pt-BR
任何解决问题的线索都将是非常可观的。