[英]Limit the number of consumers for a queue who are running parallel
我正在使用队列,有两个线程。 一种用于入队,另一种用于出队。 分别称为生产者和消费者。 生产可以是无限的。 但是我需要限制同时运行的使用者。 我读了“任务并行库”和“ Parallel.For”。 但是我不确定应该在这里实现它们的方式。 请建议我。 以下是一些代码段,可帮助您更好地理解问题
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);
}
}
使用一种常见技术来处理具有固定并行度的BlockingCollection
。 在Parallel.ForEach
选项中指定DOP。
然后,使处理功能等待子进程:
process.Start();
process.WaitForExit();
这样,您随时都有固定数量的未完成子进程。
您还可以考虑TPL Dataflow
库,可以轻松实现Producer/Consumer
模式:
private static BufferBlock<int> m_buffer = new BufferBlock<int>>(
new DataflowBlockOptions { BoundedCapacity = 10, MaxDegreeOfParallelism = 4 });
// Producer
private static async void Producer()
{
while(true)
{
await m_buffer.SendAsync(Produce());
}
}
// Consumer
private static async Task Consumer()
{
while(true)
{
Process(await m_buffer.ReceiveAsync());
}
}
您可以看到BoundedCapacity
用于节流技术,限制了队列大小,而MaxDegreeOfParallelism
用于限制并行消耗任务。
您可以在此处从MSDN下载TPL Dataflow
简介 。
PS: 如何:在MSDN上实现生产者-消费者数据流模式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.