[英]c# - running multiple sets of parallel threads (Parallel.ForEach)
[英]C# Updating multiple xml files using Parallel.ForEach
现在我正在 foreach 循环中更新大型多个文件,这需要时间。 很想知道我可以使用Parallel.ForEach同时更新多个大型 xml 文件但不想使用Lock()
我是Parallel.ForEach 的新手,所以害怕竞争条件和 xml 文件的不正确更新。 文件中的数据不应重叠。 这是一个示例代码。 所以请大家看看我的代码并告诉我我的代码在生产中工作正常吗?
List<string> listoffiles = new List<string>();
listoffiles.Add(@"d:\test1.xml");
listoffiles.Add(@"d:\test2.xml");
listoffiles.Add(@"d:\test3.xml");
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(listoffiles, options, (filepath) =>
{
XDocument xmlDoc = XDocument.Load(filepath);
//query 10QK xml data based on section & lineitem
var items = (from item in xmlDoc.Descendants("TickerBrokerStandardDateLineitemValue")
where item.Element("TabName").Value.Trim() == data.Section
&& item.Element("StandardLineItem").Value.Trim() == data.LineItem
select item).ToList();
foreach (var item in items)
{
//element will be inserted or updated in xml when match found
if (item.Element("SectionID") == null)
{
//if SectionID element does not exist then it will be added in xml having ID
item.Add(new XElement("SectionID", data.SectionID));
}
else
{
//if SectionID element exist then it will be updated with db value
item.Element("SectionID").SetValue(data.SectionID);
}
//element will be inserted or updated in xml when match found
if (item.Element("LineItemID") == null)
{
//if LineItemID element does not exist then it will be added in xml having ID
item.Add(new XElement("LineItemID", data.LineItemID));
}
else
{
//if LineItemID element exist then it will be updated with db value
item.Element("LineItemID").SetValue(data.LineItemID);
}
if (data.Approved == 1)
{
//if approved then xfundcode will be updated
if (item.Element("XFundCode") != null)
{
//if XFundCode element exist then it will be updated with db value
item.Element("XFundCode").SetValue(data.ApprovedXFundCode);
}
}
else if (data.Approved == 0)
{
//if unapproved then xfundcode will be empty
if (item.Element("XFundCode") != null)
{
//if XFundCode element exist then it will be updated with db value
item.Element("XFundCode").SetValue(string.Empty);
}
}
}
xmlDoc.Save(filepath);
});
请用最佳方法指导我,我可以用它在短时间内更新多个大型 xml 文件。 谢谢
由于Parallel.For
每个运行案例都在更新一个单独的文件,因此您不会冒竞争条件的风险,也不需要锁。 但是不要指望奇迹 - 硬盘驱动器/SSD很可能会成为您的性能瓶颈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.