[英]Use Parallel.ForEach with XmlNodeList in C#
I already done basic foreach
loop with XmlNodeList
as given bellow. 我已经按照下面的说明使用XmlNodeList
完成了基本的foreach
循环。
Sample XML File (books.xml) 样本XML文件(books.xml)
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlNodeList xnList = doc.SelectNodes("catalog/book");
foreach (XmlNode node in xnList)
{
Console.WriteLine(node["author"].InnerText);
}
How do I convert this loop into Parallel.ForEach
? 如何将此循环转换为Parallel.ForEach
?
I've try with this code.But it's didn't work. 我已经尝试过使用此代码。但是它没有用。
Parallel.ForEach(xnList, (XmlNode node) =>
{
Console.WriteLine(node["author"].InnerText);
});
It's says Error 2 说错误2
Argument 1: cannot convert from
System.Xml.XmlNodeList
toSystem.Collections.Generic.IEnumerable<System.Xml.XmlNode>
参数1:无法从System.Xml.XmlNodeList
转换为System.Collections.Generic.IEnumerable<System.Xml.XmlNode>
XmlNodeList
implements the non-generic IEnumerable
. XmlNodeList
实现非通用IEnumerable
。 You'll need to cast it first in order to work with an IEnumerable<XmlNode>
, as that is what Parallel.ForEach
operates on: 您需要先进行转换才能使用IEnumerable<XmlNode>
,因为这是Parallel.ForEach
操作方式:
Parallel.ForEach(xnList.Cast<XmlNode>(), (XmlNode node) =>
{
Console.WriteLine(node["author"].InnerText);
});
Another tip, you can set how many parallel processes you want: 另一个技巧是,您可以设置所需的并行进程数:
Parallel.ForEach(nodes.Cast<XmlNode>(), new ParallelOptions { MaxDegreeOfParallelism =
Environment.ProcessorCount },
(XmlNode node) =>
{
string value = node.InnerText;
//Some other task
});
In above Envorinment.ProcessorCount refers to the number of logical cores the CPU reports to Windows. 在上面的Envorinment.ProcessorCount中,是指CPU报告给Windows的逻辑核心数。 I strongly suggest keeping below this number. 我强烈建议保持在这个数字以下。 I have i9 28-cores, and set to 28, pretty much locks up your machine (just leave 1-2 free). 我有i9 28核,并设置为28,几乎可以锁定您的计算机(只需留下1-2个空闲时间)。
Another use for this is that when you are debugging, it is hard to track the multi-threads breaking at the same location when you have many threads running. 这样做的另一个用途是,在调试时,当有多个线程在运行时,很难跟踪在同一位置中断的多线程。 Setting this to 1 will make it work like a regular Loop. 将此设置为1将使其像常规循环一样工作。
Be mindful of impacts of this. 注意这一点的影响。 If you are interacting with public items, remember you will have 20+ parallels calls in one hit. 如果您正在与公共物品进行互动,请记住您将在一击中进行20多次并行通话。 I have found that trying to add unique Dictionary terms for some bizarre reason tells me there are duplicates when running multithread.. works fine with just 1. 我发现出于某种奇怪的原因尝试添加唯一的Dictionary术语会告诉我运行多线程时存在重复项。.仅需1即可正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.