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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With