I am using a queue, there are two threads. One is for Enqueue, the other is for Dequeue. Which are called as producer and consumer respectively. Produce can be unlimited. But I need to limit the consumers running at the same time. I read about “Task Parallel Library” and “Parallel.For”. But I’m not sure about the way that I should implement them here. Please advise me. Here are some of code segments for you to having a better understanding of the question
static void Main(string[] args) { // The Producer code comes here // ... // The Consumer code comes here Thread consumer = new Thread(new ThreadStart(PendingBookingConsumer)); consumer.Start(); } private static void PendingBookingConsumer() { try { while (true) { if (pendingBookingsQueue != null && pendingBookingsQueue.Count > 0) { PendingBooking oPendingBooking = pendingBookingsQueue.Dequeue(); //Run the Console App string command = @"C:\ServerAgentConsole.exe"; string args = oPendingBooking.Id + " " + oPendingBooking.ServiceAccountEmail.Trim() + " " + oPendingBooking.ServiceAccountPassword.Trim() + " " + oPendingBooking.ServiceAccountEmail.Trim() + " " + oPendingBooking.MailBoxOwnerEmail.Trim() + " " + oPendingBooking.Method.Trim(); Process process = new Process(); process.StartInfo.FileName = command; process.StartInfo.Arguments = args; process.EnableRaisingEvents = true; process.Exited += (sender, e) => { Process myProcess = (Process)sender; Console.WriteLine("Agent for booking ID :" + myProcess.StartInfo.Arguments[0] + " Done"); }; process.Start(); Thread.Sleep(2); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }