由于来自microsoft的以下信息,我稍微更新了我的代码。听起来他们将当前的文化更新为我可以使用的东西。
对于面向.NET Framework 4.6及更高版本的应用, CultureInfo.CurrentCulture和CultureInfo.CurrentUICulture被存储 在一个线程的ExecutionContext中,它跨越异步 操作。 (来源:https://msdn.microsoft.com/en-us/library/dn833123(v=vs.110).aspx)
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回归en-US而不是de-DE?是因为executionContext不同吗?如果是这样,我怎样才能保持相同的执行环境?
答案 0 :(得分:2)
CurrentCulture
和CurrentUICulture
是独立的属性。您只需设置CurrentCulture
,并且您在报告CurrentUICulture
的情况下报告除了以外的所有地方<{1}}。如果你在整个代码中使用相同的属性(任何一个属性应该没问题),它会给你预期的结果。