簡體   English   中英

生產者消費者有單獨的類,具有共同的BlockingCollection

[英]Producer Consumer Separate Classes with common BlockingCollection

希望有人可以針對生產者/消費者模式提供一些建議,尤其是在如何最好地實現對所有生產者/消費者類實例通用的Queue / BlockingCollection方面?

讓我們簡化場景; 認為我有;

  • 單個生產者類
  • 一個單一的Consumer類。
  • 一個服務類,其中包含生產者類和消費者類的實例。 服務類僅告訴生產者/消費者開始和停止工作。

生產者將填充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當然很簡單,因為對該對象的引用是同一類中的私有成員。

如果我將Producer和Consumer分為不同的類,那么這將引發一個問題,即如何擁有一個公共的BlockingCollection。

我應該將“服務類”設為靜態/共享類,在此類中創建BlockingCollection並將其公開為朋友/公共成員嗎?

我應該把通用隊列放在哪里?

提前致謝!

只需將您的ProducerConsumer類設計為接受BlockingCollection作為構造函數參數即可。

然后,無論您在何處實例化這些類,甚至可能實例化多個類,只需確保將BlockingCollection的相同實例傳遞給所有生產者和消費者。 完成此操作后,無需保留對BlockingCollection其他外部引用,除非您需要其他引用。 每個ProducerConsumer擁有對同一BlockingCollection實例的私有引用就足夠了。

基本上,它看起來像這樣:

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.
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM