Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent collection for .NET with timeouts?

I have a concurrent collection.

var q = new ConcurrentQueue<int>(); // Or a stack/bag/etc...

I can get an item like this.

int i;
if (q.TryDequeue(out i))
    DoStuff(i);

But I need it like "wait 10 seconds before returning false in case someone adds a new item":

int i;
if (q.TryDequeue(TimeSpan.FromSeconds(10), out i))
    DoStuff(i);

I could write an extension method like this:

public static bool TryDequeue<T>(
    this ConcurrentQueue<T> queue,
    TimeSpan timeout,
    out T result)
{
    // Validations...

    for (int i = 0; i < 2; i++)
    {
        if (queue.TryDequeue(out result))
            return true;
        else if (i == 1)
            return false;

        Thread.Sleep(timeout);
    }
}

But what if someone adds an item to the queue in 5 seconds, I don't want to wait 5 more.

Is there any thread-safe collection that supports this feature in .NET?

like image 951
Şafak Gür Avatar asked Apr 10 '13 14:04

Şafak Gür


1 Answers

Rather than use ConcurrentQueue directly, you should wrap it in a BlockingCollection. You can then use TryTake(out T, TimeSpan).

BlockingCollection is specifically designed for producer/consumer scenarios. (You should look at TPL Dataflow at the same time, mind you.)

like image 194
Jon Skeet Avatar answered Oct 22 '22 08:10

Jon Skeet