如何在并行块中正确继承线程文化?

时间:2016-03-21 13:26:50

标签: c# asp.net-mvc multithreading globalization currentculture

我在ASP MVC网站上使用自动全球化。它工作正常,直到达到并行块:

public ActionResult Index() 
{
     // Thread.CurrentThread.CurrentCulture is automatically set to "fr-FR"
     // according to the requested "Accept-Language" header

     Parallel.Foreach(ids, id => {
        // Not every thread in this block has the correct culture. 
        // Some of them still have the default culture "en-GB"
     }) ; 

     return View()
}

使并行块继承文化的最佳方法是什么?除了这个解决方案:

public ActionResult Index() 
{
     var currentCulture = Thread.CurrentThread.CurrentCulture  ;

     Parallel.Foreach(ids, id => {
         // I don't know if it's threadsafe or not. 
         Thread.CurrentThread.CurrentCulture = currentCulture ; 

     }) ; 

     return View()
}

1 个答案:

答案 0 :(得分:3)

您可以创建自己的Parallel.ForEach处理线程文化:

public static class ParallelInheritCulture
{
    public static ParallelLoopResult ForEach<T>(IEnumerable<T> source, Action<T> body)
    {
        var parentThreadCulture = Thread.CurrentThread.CurrentCulture; 
        var parentThreadUICulture = Thread.CurrentThread.CurrentUICulture; 

        return Parallel.ForEach(source, e =>
        {
            var currentCulture = Thread.CurrentThread.CurrentCulture; 
            var currentUICulture = Thread.CurrentThread.CurrentUICulture; 

            try
            {
                Thread.CurrentThread.CurrentCulture = parentThreadCulture;
                Thread.CurrentThread.CurrentUICulture = parentThreadUICulture;

                body(e); 
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = currentCulture;
                Thread.CurrentThread.CurrentUICulture = currentUICulture;
            }
        }); 
    }
}

然后:

 ParallelInheritCulture.Foreach(ids, id => {
    // Whatever

 }) ;