C# WinForms MultiThreading in Loop
- by Goober
Scenario
I have a background worker in my application that runs off and does a bunch of processing. I specifically used this implementation so as to keep my User Interface fluid and prevent it from freezing up. I want to keep the background worker, but inside that thread, spawn off ONLY 3 MORE threads - making them share the processing (currently the worker thread just loops through and processes each asset one-by-one. However I would like to speed this up but using only a limited number of threads.
Question
Given the code below, how can I get the loop to choose a thread that is free, and then essentially wait if there isn't one free before it continues.
CODE
foreach (KeyValuePair<int, LiveAsset> kvp in laToHaganise)
{
Haganise h = new Haganise(kvp.Value,
busDate,
inputMktSet,
outputMktSet,
prodType,
noOfAssets,
bulkSaving);
h.DoWork();
}
Thoughts
I'm guessing that I would have to start off by creating 3 new threads, but my concern is that if I'm instantiating a new Haganise object each time - how can I pass the correct "h" object to the correct thread.....
Thread firstThread = new Thread(new ThreadStart(h.DoWork));
Thread secondThread =new Thread(new ThreadStart(h.DoWork));
Thread thirdThread = new Thread(new ThreadStart(h.DoWork));
Help greatly appreciated.