0

I have a program of mine which makes use of the c# concurrent Queue to pass data from my one component to the other.

Component 1: Multiple network connections receive data and then put it into this Queue

Component 2: Reads data from this queue and then processes it.

Ok, good all makes sense ( I sure hope).

Now what I want to know, is what is the best / most efficient way to go about passing the data between the two components?

Option 1: Poll the queue for new data in component 2? Which will entail blocking code, or atleast a while(true)

Option 2: I don't know if this is possible, but that's why im here asking. Does the queue data structure not have a sort of functionality that say my component 2 can register to the queue to be notified of any inserts / changes? This way whenever data is added it can just go fetch it, and I can then avoid any blocking / polling code.

4

2 回答 2

2

对于生产者/消费者的简单实现,您可以尝试使用BlockingCollection。对于来自各种来源的更复杂的数据消耗,Reactive Extensions可能会有所帮助。这是一个更陡峭的学习曲线,但它是一个非常强大的基于拉的框架,所以你不需要做任何轮询。

于 2014-05-12T10:19:52.870 回答
2

组件 1(生产者)需要手动或自动阻止,因为您预计在生产时会进行多次访问(提到多个帖子)。这意味着 BlockingQueue 在 Component1 中有意义。但是,在组件 2(消费者)中,如果您认为您(在任何时候)只有一个消费者,那么您不需要任何阻塞代码。

为了节省或避免while,您必须需要一种机制来通知消费者有人已将某些内容添加到队列中。这可以使用自定义事件(不谈论 EventHandle 子类型)来实现。请记住,您可能没有这种事件风格的元素顺序。

于 2014-05-12T10:29:49.723 回答