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

1

6

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?

Merchant answered 30/11, 2016 at 19:18 Comment(1)
Culture can be stored as a thread local. If you changed the culture of the active thread it does not affect thread pool threads.Roy
T
8

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)

Tine answered 30/11, 2016 at 19:56 Comment(2)
Thanks for the answer! You are correct. Unfortunately this application is still using 4.0 with no option to change this before the next release. I resolved to setting the culture settings just inside the loop. Appreciated!Merchant
Your're welcome, As you said you can set culture thread inside the loop.Tine

© 2022 - 2024 — McMap. All rights reserved.