0

背景:

我有一个异步等待函数,它从外部源获取语言和区域设置参数,这将用于设置为 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

任何解决问题的线索都将是非常可观的。

4

1 回答 1

1

我假设你不希望你的主线程在它的文化集之前做任何其他事情。这对我来说似乎是一个合理的假设。

在这种情况下,您可以阻塞主线程:

public static async Task Main()
{
  // Nothing should use await before this line.
  var cultureText = externalService.GetCultureAsync().GetAwaiter().GetResult();
  Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureText);

  // Other code that can use await.
}

如果这是一个 UI 应用程序,那么您可以在后台线程上运行异步代码:

public static async Task Main()
{
  // Nothing should use await before this line.
  var cultureText = Task.Run(() => externalService.GetCultureAsync()).GetAwaiter().GetResult();
  Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureText);

  // Other code that can use await.
}
于 2021-04-08T17:58:45.173 回答