[英]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.