我正在开发一个ASP.NET Web API项目,其中我遇到一个问题,Task即异步运行的子进程没有继承父线程的当前文化; 即,Thread.CurrentThread.CurrentUICulture在控制器构造函数中设置之后,Task除非我单独设置,否则在操作中创建的任何文件都默认具有不变文化.这似乎已经在框架> 4.0中修复,并且在将目标框架升级3.5.2到4.6.2 此处提到之后工作正常.
从面向.NET Framework 4.6的应用程序开始,即使任务在线程池线程上异步运行,调用线程的文化也会被每个任务继承.
现在,任务中的文化继承按预期工作,我面临另一个奇怪的问题,这个问题在4.5.2中没有出现.如果WebApi操作结果是类型IEnumerable,则结果将具有默认文化.也许使用示例代码段可以更好地解释问题:
public SampleController()
{
System.Threading.Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo("ar-AE");
}
[Route]
public IHttpActionResult Get()
{
IEnumerable<Employee> employeesDeferred = BuildEmployees(true);
return Ok(employeesDeferred);
}
private IEnumerable<Employee> BuildEmployees(bool isDeferred)
{
var employees = Enumerable.Range(0, 2)
.Select(count => new Employee
{
Id = count++,
Culture = Thread.CurrentThread.CurrentUICulture.Name
});
if (isDeferred) { return employees; }
return employees.ToList();
}
Run Code Online (Sandbox Code Playgroud)
请注意,我在构造函数中将UI文化设置为"ar-AE".PFB结果: