由于Microsoft提供了以下信息,因此我对代码进行了一些更新。听起来他们将当前的文化更新为我可以使用的东西。
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("start " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
RunAsync().Wait();
Console.WriteLine("Finish " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
static async Task RunAsync()
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
Console.WriteLine("1 " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
string cultureInTask = string.Empty;
await Task.Run(() => cultureInTask = Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId).ConfigureAwait(true);
Console.WriteLine("2 " + cultureInTask);
string twoA = await TestMethodAsync();
Console.WriteLine("2a " + twoA + " " + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("3 " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
}
public static async Task<string> TestMethodAsync()
{
Console.WriteLine("2s " + Thread.CurrentThread.CurrentCulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
return await Task.Run(() =>
{
return System.Threading.Thread.CurrentThread.CurrentUICulture.ToString() + " " + Thread.CurrentThread.ManagedThreadId;
});
}
}
输出:
start en-US 1
1 de-DE 1
2 de-DE 3
2s de-DE 3
2a en-US 4 4
3 de-DE 4
Finish en-US 1
但是为什么2a返回美国而不是de-DE?是因为executionContext不同吗?如果是这样,我如何才能留在相同的执行上下文中?
最佳答案
CurrentCulture
和CurrentUICulture
是独立的属性。您只设置CurrentCulture
,并且在除2a以外的所有位置报告该位置,该位置报告CurrentUICulture
。如果您在代码中始终使用相同的属性(两个属性都可以),它将为您带来预期的结果。
关于c# - .net-4.6中的异步Thread.CurrentThread.CurrentCulture,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44392456/