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

How to correctly inherit thread culture in a parallel block?

我在 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()
}

您可以创建自己的 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

 }) ;