views:

105

answers:

1

I have a Semaphore that runs trough a list of Job objects.

Here is a sample of the code:

List<Job> jobList = jobQueue.GetJobsWithStatus(status);
if (jobList.Count > 0)
{
  foreach (Job job in jobList)
  {
    semaphore.WaitOne();

    // Only N threads can get here at once
    job.semaphore = semaphore;
    ThreadStart threadStart = new ThreadStart(job.Process);

    Thread workerThread = new Thread(threadStart);
    workerThread.Start();
  }

  //check that every thread has completed before continuing
}

Every job object has a status member variablea (0: new, 1: inProgress, 2: completed, 3: completedWithErrors).

I was wondering what is the best way to check that every job in the list has completed before continuing with the script.

Note: I tried before with a ThreadPool and WaitAll, but It doenst allow me to have a limited amount of threads (without secondary effects) like a semaphore does, and I also hit a limitation of the size of the ManualResetEvent array because it is a Windows Form.

+1  A: 

You can normally call Thread.Join on each thread in a separate foreach loop.

By the way, you can combine the semaphore with the thread pool: have each work item wait on the semaphore before doing any work.

Tim Robinson