BlockingCollection

19 08 2011

When you call TryTake on a ConcurrentQueue, ConcurrentBag or ConcurrentStack and the collection is empty you get false. In producer/consumer situations you often use events to wait when a collection is empty and signal when it is not. A blocking collection wraps any collection that implements IProducerConsumerCollectionand provides this wait and signal functionality for you. So when you call TryTake on a BlockingCollection the calling thread blocks until there are items present.

To use BlockingCollection:

1. Instantiate the class, optionally specifying the IProducerConsumerCollectionto wrap and the maximum size (bound) of the collection.

2. Call Add or TryAdd to add elements to the underlying collection.

3. Call Take or TryTake to remove (consume) elements from the underlying collection.

If you call the constructor without passing in a collection, the class will default to instantiating a ConcurrentQueue.

Another way to consume elements is to call GetConsumingEnumerable. This returns a (potentially) infinite sequence that yields elements as they become available. You can force the sequence to end by calling CompleteAdding: this method also prevents further elements from being enqueued.

Here is an example from my OrderMatchingEngine project:

public class DedicatedThreadOrderProcessor : OrderBook.OrderProcessor
{
    private readonly Thread m_Thread;
    private readonly BlockingCollection m_PendingOrders = new BlockingCollection();

    public DedicatedThreadOrderProcessor(BuyOrders buyOrders, SellOrders sellOrders, Trades trades)
        : base(buyOrders, sellOrders, trades)
    {
        m_Thread = new Thread(ProcessOrders);
        m_Thread.Start();
    }

    private void ProcessOrders()
    {
        foreach (var order in m_PendingOrders.GetConsumingEnumerable())
        {
            ProcessOrder(order);
        }
    }

    public void Stop()
    {
        this.m_PendingOrders.CompleteAdding();
    }

    public override void InsertOrder(Order order)
    {
        m_PendingOrders.Add(order);
    }

}
Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: