I have made a service which reads an xml. In the xml i have Input directory and output directory. The service picks the files in the input directory and renames them and moves them to the output directory. I want to implement threading in the service. I want it to pick one node of xml in one thread and other in the other. Or it would even be good if irrespective of nodes one thread picks the first 10 operations to be performed and the next the next 10 and so on. So that all the nodes are processed in a parallel fashion. Can anyone help me on this? i tried reading through a few threading tutorials but could not gain much through them. The service code is as follows:
XmlDocument doc = new XmlDocument();
doc.Load("Data.xml");
int count = doc.SelectNodes("Data/DataClass").Count;
for (int i = 1; i < count; i++)
{
string xpath = "/Data/DataClass[" + i + "]";
XmlNode node = doc.SelectSingleNode(xpath);
XmlNodeList subnode = node.ChildNodes;
string pathO = "";
string pathI = subnode[0].InnerText;
string prefix = subnode[2].InnerText;
string freq = subnode[3].InnerText;
string[] filenames = Directory.GetFiles(pathI);
node.ParentNode.RemoveChild(doc.SelectSingleNode(xpath));
doc.Save("Data.xml");
foreach (string filename in filenames)
{
pathO = subnode[1].InnerText;
pathO = pathO + "\\" + prefix;
string fname = Path.GetFileName(filename);
pathO = pathO + fname;
System.IO.File.Move(filename, pathO);
}
}
Use Parallel.For or Parallel.ForEach, check the following code, its simple , i’ve modified your code here only so check it with VS (there maybe small changes as per your requirement).
Don’t remove the child node inside Parallel loop so i removed the following line
node.ParentNode.RemoveChild(node);
Learn more about Task Parallel Liberary (http://msdn.microsoft.com/en-us/library/dd537608.aspx) for parallel processing features given.