[英]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": 但是我需要它像“在有人添加新项目之前等待10秒再返回假”:
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. 但是如果有人在5秒钟内将一个项目添加到队列中,我不想再等5个。
Is there any thread-safe collection that supports this feature in .NET? 是否有任何线程安全的集合在.NET中支持此功能?
Rather than use ConcurrentQueue
directly, you should wrap it in a BlockingCollection
. 您应该将它包装在
BlockingCollection
,而不是直接使用ConcurrentQueue
。 You can then use TryTake(out T, TimeSpan)
. 然后,您可以使用
TryTake(out T, TimeSpan)
。
BlockingCollection
is specifically designed for producer/consumer scenarios. BlockingCollection
专为生产者/消费者场景设计。 (You should look at TPL Dataflow at the same time, mind you.) (请注意,您应该同时查看TPL Dataflow 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.