希望有人可以就生产者/消费者模式提供一些建议——特别是如何最好地实现对所有生产者/消费者类实例COMMON的 Queue/BlockingCollection?
让我们简化场景;考虑我有;
- 一个生产者类
- 单个消费者类。
- 一项服务 包含生产者和消费者实例的类 类(class)。服务类只是告诉生产者/消费者开始 并停止工作。
生产者将填充一个 BlockingCollection
消费者需要从同一个 BlockingCollection 中读取
如本文所示,这一切都非常容易做到;
https://msdn.microsoft.com/en-us/library/dd287186.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
这个例子本质上在同一个类中有 PRODUCER 和 CONSUMER,引用 Common Queue/BlockingCollection 当然是微不足道的,因为对对象的引用是对同一个类中的私有(private)成员。
如果我将 Producer 和 Consumer 分离到不同的类中,那么这就提出了如何拥有一个公共(public) BlockingCollection 的问题。
我是否应该将“服务类”设为静态/共享类,在此类中创建 BlockingCollection 并将其公开为 friend /公共(public)成员?
common Queue应该放在哪里?
提前致谢!
最佳答案
只需将 Producer
和 Consumer
类设计为接受 BlockingCollection
作为构造函数参数即可。
然后,无论您在何处实例化这些类,甚至可能不止一个,只需确保将相同的 BlockingCollection
实例传递给所有生产者和消费者。完成此操作后,无需保留对 BlockingCollection
的一些其他外部引用,除非您需要它用于其他用途。每个 Producer
和 Consumer
都持有对同一 BlockingCollection
实例的私有(private)引用就足够了。
基本上,它看起来像这样:
public class Producer {
private BlockingCollection queue;
public Producer(BlockingCollection queue) {
this.queue = queue;
}
// more code...
}
public class Consumer {
private BlockingCollection queue;
public Consumer(BlockingCollection queue) {
this.queue = queue;
}
// more code...
}
// The exact design of this class is up to you. This is just an example.
public class ProducerConsumerBuilder {
public void BuildProducerAndConsumer(out Producer producer, out Consumer consumer) {
BlockingCollection queue = new BlockingCollection();
producer = new Producer(queue);
consumer = new Consumer(queue);
// No need to save a reference to "queue" here any longer,
// unless you need it for something else.
// It's enough that the producer and consumer each
// hold their own private reference to the same queue.
}
}
关于c# - 生产者消费者使用公共(public) BlockingCollection 分离类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30804145/