Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

process list items in different threads

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.

like image 735
Benjamin Ortuzar Avatar asked Sep 05 '26 11:09

Benjamin Ortuzar


2 Answers

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

Parallel.ForEach(jobList, curJob => {
  curJob.Process()
});
like image 139
Ron Warholic Avatar answered Sep 07 '26 02:09

Ron Warholic


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.

like image 24
Nick Larsen Avatar answered Sep 07 '26 02:09

Nick Larsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!