请看下面的伪代码
//Single or multiple Producers produce using below method
void Produce(object itemToQueue)
{
concurrentQueue.enqueue(itemToQueue);
consumerSignal.set;
}
//somewhere else we have started a consumer like this
//we have only one consumer
void StartConsumer()
{
while (!concurrentQueue.IsEmpty())
{
if (concurrentQueue.TrydeQueue(out item))
{
//long running processing of item
}
}
consumerSignal.WaitOne();
}
我如何移植这个我自古以来就用来使用taskfactory创建的任务和NET4的新信令特性的模式。换句话说,如果有人使用NET4编写这个模式,它会是什么样子?伪代码很好。正如你所见,我已经在使用.net 4 concurrentQueue了。我如何使用一个任务,如果可能的话,还可能使用一些新的信令机制。谢谢
感谢Jon/Dan,我的问题在下面得到了解决。甜。没有手动信令或while(true)或while(itemstoProcess)类型的循环
//Single or multiple Producers produce using below method
void Produce(object itemToQueue)
{
blockingCollection.add(item);
}
//somewhere else we have started a consumer like this
//this supports multiple consumers !
task(StartConsuming()).Start;
void StartConsuming()
{
foreach (object item in blockingCollection.GetConsumingEnumerable())
{
//long running processing of item
}
}
cancellations are handled using cancel tokens
发布于 2011-06-29 03:36:43
您将使用BlockingCollection
。文档中有一个示例。
这个类是专门设计的,目的是让这件事变得微不足道。
发布于 2011-06-29 03:35:20
在此之前,我使用了一种模式来创建一种“按需”队列消费者(基于从ConcurrentQueue消费):
private void FireAndForget(Action fire)
{
_firedEvents.Enqueue(fire);
lock (_taskLock)
{
if (_launcherTask == null)
{
_launcherTask = new Task(LaunchEvents);
_launcherTask.ContinueWith(EventsComplete);
_launcherTask.Start();
}
}
}
private void LaunchEvents()
{
Action nextEvent;
while (_firedEvents.TryDequeue(out nextEvent))
{
if (_synchronized)
{
var syncEvent = nextEvent;
_mediator._syncContext.Send(state => syncEvent(), null);
}
else
{
nextEvent();
}
lock (_taskLock)
{
if (_firedEvents.Count == 0)
{
_launcherTask = null;
break;
}
}
}
}
private void EventsComplete(Task task)
{
if (task.IsFaulted && task.Exception != null)
{
// Do something with task Exception here
}
}
https://stackoverflow.com/questions/6512033
复制相似问题