Having read the MSDN How To: document on using parallel.foreach() I thought I might be able to parallelise some long-running parts of my code - however Visual Studio is producing an error message that I'm struggling to understand, and I'm no longer sure that an XmlNodeList
is an System.Collections.IEnumerable
or not!
My code is:
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)
I then get the error message:
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.
Where am I going wrong?
The XmlNodeList
class does implement the IEnumerable
interface. However, Parallel.ForEach
expects an IEnumerable(Of T)
parameter (or, in this case, IEnumerable(Of XmlNode)
). Therefore, the overload resolution fails. You need to cast the XmlNodeList
object to IEnumerable(Of XmlNode)
.
Try something like this:
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)