Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Parallel.ForEach change the culture of its threads?

Today I came across a strange phenomenon I can't really explain. There's a webpage with a number of rows in a gridview, which need to be saved to the database and to an XML file one by one. I ended up using a Parallel.ForEach, as there is no relation between the rows, so they can be executed independently. The code is basically this:

        Parallel.ForEach(gvWithData.Rows.Cast<GridViewRow>(), row =>
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                    // do some logic and stuff...
                    var type = new Object { ... };

                    // save to the database
                    type.Save();

                    // retrieve the saved item from the database again
                    //  since we need some autoincrement values from the db
                    var typeAfterSave = TypeManager.GetFromDb();

                    // create a custom XML from the object
                    XmlManager.CreateXml(typeAfterSave);
                }
            }

Why on earth would this code work any different when I replace the Parallel.ForEach with a good old foreach and I change nothing else?

The difference is that the culture in which the XML is created in the first case is different from the second case, and I have not the slightest clue why.

Any suggestions?

like image 408
MeanGreen Avatar asked Nov 30 '16 19:11

MeanGreen


1 Answers

It's because you've set culture for the CurrentThread. Parallel.ForEach will create a new Task for every iteration, which they will have the default culture.

In .NET 4.5, you can use the CultureInfo.DefaultThreadCurrentCulture property to change the culture of an AppDomain ( set the culture for all threads ).

(CultureInfo.DefaultThreadCurrentCulture on msdn)

like image 141
Ali Bahrami Avatar answered Nov 14 '22 21:11

Ali Bahrami