C# WinForms MultiThreading in Loop

Posted by Goober on Stack Overflow See other posts from Stack Overflow or by Goober
Published on 2010-04-09T08:07:35Z Indexed on 2010/04/09 8:13 UTC
Read the original article Hit count: 298

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading