Translate

Thursday 27 August 2009

Parallel.For XML Parsing

Another example using Parallel.For. Depending upon the cores in your machine, you will find the code returning different results. MaxDegreeOfParallelism sets the max number of cores to be used for running the parallel forloop.

class Program
{
static void Main(string[] args)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("e:\\JKTAgileAcademy_August2009\\cd_catalog.xml");
XmlNodeList title = xDoc.GetElementsByTagName("CD");
XmlNode xNode=null;
var options = new ParallelOptions { MaxDegreeOfParallelism = 2 };
Stopwatch sw=new Stopwatch();
sw.Start();
Parallel.For(0, title.Count, options, (j) => //() => title, (x, loop, xN) =>
{
xNode = title.Item(j);
Console.WriteLine("Inner XML from Nodelist" + xNode.InnerText);
j++;
}
);
sw.Stop();
Console.WriteLine("Time taken by parallel loop " + sw.ElapsedMilliseconds.ToString());
//sw.Reset();
sw.Start();
for (int i = 0; i < title.Count; i++)
{
xNode = title.Item(i);
Console.WriteLine(xNode.InnerText);
}
sw.Stop();
Console.WriteLine("Time taken by for loop " + sw.ElapsedMilliseconds.ToString());

Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}

No comments: