基于事件的多线程生产者-消费者?
我想弄清楚如何创建一个基于外部事件的多线程生产者/消费者程序.
I wish to figure out how to create a multithreaded producer/consumer program where producing is based on an external event.
我建立了一个具有2个线程循环的同步队列,其中一个循环进入队列,一个循环出队并写入文件,具有经典模式:
I have built a synchronized queue having 2 thread loops, one to enqueue and one to dequeue and write into a file, with classic pattern:
Class SyncQueue
{
...
producerThread = new Thread(new ThreadStart(StartProducer));
consumerThread = new Thread(new ThreadStart(StartConsumer));
...
public void Start()
{
producerThread.Start();
consumerThread.Start();
}
public void StartProducer()
{
while (!stop)
{
//wait for an external event to happen
//Data data = eventHandler() : How to wait for an event and get?
Enqueue(data);
}
}
}
另一方面,我在另一个类中有一个方法可以独立处理外部事件.
In the other side, I have a method in another class that handles an external event independantly.
public void OnExternalEvent()
{
//event occured
//how to notify and send data to the producer thread?
}
我的问题不是关于生产者/消费者模式,而是关于在其中集成事件.
My question in not about the producer/consumer pattern, but it's about integrating events among it.
我发布的代码只是为了使我的问题更清楚,我在注释中添加了两个具体的问题.
The code I posted is just to make my question clearer, I added two concrete questions in comments.
如果有人能告诉我该怎么做,我将不胜感激.我是C#的新手,对事件处理没有很深的了解.
I would appreciate if anyone can tell me how to do it. I am new in C# and do not have a strong background with event handling.
Ditch your custom synchronized queue and use a BlockingCollection< T >.
使用BlockingCollection
,您没有单独的线程来控制队列.相反,您有一个队列,线程可以直接使项目入队或出队.数据结构本身可以处理任何并发问题,并且在尝试出队时不忙等待.
With BlockingCollection
, you don't have separate threads controlling the queue. Rather, you have a queue, and threads can directly enqueue or dequeue items. The data structure itself handles any concurrency issues, and does non-busy waits when trying to dequeue.
请参见 https://stackoverflow.com/a/19848796/56778 和https://stackoverflow.com/a/19823345/56778 作为示例,或者只是搜索一下.另外,请参阅我的简单多线程博客文章以了解多一点细节.
See https://stackoverflow.com/a/19848796/56778 and https://stackoverflow.com/a/19823345/56778 for examples, or just search around a bit. Also, see my Simple Multithreading blog post for a little bit more detail.