views:

68

answers:

5

At the moment I have List of Job objects that are queued to be processed sequentially shown in the code bellow.

   List<Job> jobList = jobQueue.GetJobsWithStatus(Status.New);
   foreach (Job job in jobList)
   {               
        job.Process();
   }

I am interested in running several Jobs at the same time in a limited number of threads (lets say 5 threads).

What is the best way to do this in c#?

Additional Notes:

  • A Job object does not share resources with other jobs.
  • Each Job takes about 10 seconds to process.
  • Each job could connect to different resources.

Update: I have used a Semaphore because I could not limit the amount of active threads with a ThreadPool.

+2  A: 

You will want to look into thread pools (for the simple answer). There is even a ThreadPool class in C# and it is quite easy to set up with great examples in the msdn library.

NickLarsen
A: 

If you meant to use Threading, simple coding:

private static void TransferThread(ThreadStart tstart)
        {
            Thread thread = new Thread(tstart);
            thread.IsBackground = true;
            thread.Start();
}

Or you can you ThreadPool. This allows you to use any available thread and return it back to the pool after you're done.

madatanic
+4  A: 

If you're feeling adventurous you can use C# 4.0 and the Task Parallel Library:

Parallel.ForEach(jobList, curJob => {
  curJob.Process()
});
Ron Warholic
+1 : Depending on the version that you can run with this is probably going to be one of the best answers. It's simple to implement and is also scalable such that it will only spawn off threads while the CPU is underworked.
Ian
Very interesting Sid, At the moment I am using Visual Studio 2008 with .NET 3.5. Sadly, I don't think I will be able to use 4.0 on the live servers until it becomes Gold.
Benjamin Ortuzar
Understandable, I'm still stuck using .NET 2.0 :(
Ron Warholic
+1  A: 

ThreadPool.QueueUserWorkItem()

This will queue a method for execution. It will execute when a thread pool thread is available.

Ardman
A: 

I would give the .NET ThreadPool a try.

Pawel Pabich