I was trying out a very simple Producer Consumer approach using BlockingCollection
as per the article described here: MS Docs to understand multithreading.
My producer is a single task which reads from an XML file (has around 4000 nodes) and pushes XElement
nodes to a blocking collection.
My consumer will have multiple threads reading from the blocking collection and uploading files to a site based on the XElement
.
The problem here is that the program unexpectedly closes every time I try to run it. It hits the producer Task.Run
but stops after that. I'm not able to understand the reason why. Am I doing something wrong? It doesn't even hit the catch
block.
Code is below:
BlockingCollection<XElement> collection = new BlockingCollection<XElement>(100);
string metadataFilePath = exportLocation + listTitle + "\\Metadata\\" + exportJobId + ".xml";
//create the producer
Task.Run(() =>
{
//Process only the files that have not been uploaded
XDocument xmlFile = XDocument.Load(metadataFilePath);
var query = from c in xmlFile.Elements("Items").Elements("Item")
where c.Attribute("IsUploaded").Value == "No"
select c;
foreach (var item in query)
{
collection.Add(item);
}
collection.CompleteAdding();
});
//process consumer
Parallel.ForEach(collection, (new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = 2 }), (metadata) => {
ProcessItems();
});
Parallel.ForEach()
? Maybe you need to put alock
around thecollection.Add()
statement – mikeyq6BlockingCollection
– mikeyq6