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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With