Parallel.ForEach() 可以用在 Xml 文档上吗?

Can Parallel.ForEach() be used on an Xml document?

阅读 MSDN How To: document on using parallel.foreach() 后,我认为我可以并行化我的代码的某些长 运行 部分 - 然而 Visual Studio 产生了一条错误消息,我正在努力理解,我不再确定 XmlNodeListSystem.Collections.IEnumerable 还是不是!

我的代码是:

Parallel.ForEach(Doc.GetElementsByTagName("Details2"), Sub(Node As XmlNode)
      'do something, for instance
      For Each tAttribute As XmlAttribute In Nodede.Attributes
          debug.writeline(tAttribute.value)
      next
   End Sub)

然后我收到错误消息:

Error BC30518 Overload resolution failed because no accessible 'ForEach' can be called with these arguments: 'Public Shared Overloads Function ForEach(Of TSource)(source As IEnumerable(Of TSource), body As Action(Of TSource)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.

我哪里错了?

XmlNodeList class 确实实现了 IEnumerable 接口。但是,Parallel.ForEach 需要一个 IEnumerable(Of T) 参数(或者,在这种情况下,IEnumerable(Of XmlNode))。因此,重载决议失败。您需要将 XmlNodeList 对象转换为 IEnumerable(Of XmlNode).

尝试这样的事情:

Parallel.ForEach(doc.GetElementsByTagName("Details2").OfType(Of XmlNode),
                 Sub(node As XmlNode)
                     'do something, for instance
                     For Each tAttribute As XmlAttribute In node.Attributes
                         Debug.WriteLine(tAttribute.Value)
                     Next
                 End Sub)