我在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

 }) ;

关于c# - 如何在并行块中正确继承线程文化?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36132317/

10-10 22:13