为什么Parallel.ForEach会改变其线程的区域性? [英] Why does Parallel.ForEach change the culture of its threads?
问题描述
今天,我遇到了一个无法解释的奇怪现象。在gridview中有一个包含许多行的网页,需要将它们逐一保存到数据库和XML文件中。我最终使用了 Parallel.ForEach
,因为行之间没有关系,所以它们可以独立执行。代码基本上是这样的:
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);
}
}
为什么当这段代码的工作原理不同时,我将 Parallel.ForEach
替换为旧的 forea ch
和我什么都没改变吗?
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?
不同之处在于在XML中创建XML的文化第一种情况与第二种情况不同,我也不知道为什么。
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.
有任何建议吗?
推荐答案
这是因为您为 CurrentThread 设置了区域性。 Parallel.ForEach
将为每次迭代创建一个新的 Task
,它们将具有默认区域性。
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.
在.NET 4.5中,您可以使用 CultureInfo.DefaultThreadCurrentCulture
属性更改 AppDomain的区域性
(为所有线程设置区域性)。
In .NET 4.5, you can use the CultureInfo.DefaultThreadCurrentCulture
property to change the culture of an AppDomain
( set the culture for all threads ).
( msdn上的CultureInfo.DefaultThreadCurrentCulture )
这篇关于为什么Parallel.ForEach会改变其线程的区域性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!