我有一个多生产者和单一消费者的情况,我选择了一个共同的thread-safe资源,其中所有生产者Enqueue项目。但是,我不知道如何有效地使生产者await为新的项目时,Dequeue-ing从该资源。
POCO
struct Sample
{
public int Id { get; set; }
public double Value { get; set; }
}Producers
class ProducerGroup
{
StorageQueue sink;
int producerGroupSize;
public ProducerGroup(StorageQueue _sink,int producers)
{
this.sink = _sink;
this.producerGroupSize = producers;
}
public void StartProducers()
{
Task[] producers = new Task[producerGroupSize];
int currentProducer;
for (int i = 0; i < producerGroupSize; i++)
{
currentProducer = i;
producers[i] = Task.Run(async () =>
{
int cycle = 0;
while (true)
{
if (cycle > 5)
{
cycle = 0;
}
Sample localSample = new Sample { Id = currentProducer, Value = cycle++ };
await Task.Delay(1000);
this.sink.Enqueue(localSample);
}
});
}
}
}存储
class StorageQueue
{
private TaskCompletionSource<Sample> tcs;
private object @lock = new object();
private Queue<Sample> queue;
public static StorageQueue CreateQueue(int?size=null)
{
return new StorageQueue(size);
}
public StorageQueue(int ?size)
{
if (size.HasValue)
{
this.queue = new Queue<Sample>(size.Value);
}
else
this.queue = new Queue<Sample>();
}
public void Enqueue(Sample value)
{
lock (this.@lock)
{
this.queue.Enqueue(value);
tcs = new TaskCompletionSource<Sample>();
tcs.SetResult(this.queue.Peek());
}
}
public async Task<Sample> DequeueAsync()
{
var result=await this.tcs.Task;
this.queue.Dequeue();
return result;
}
}Consumer
class Consumer
{
private StorageQueue source;
public Consumer(StorageQueue _source)
{
this.source = _source;
}
public async Task ConsumeAsync()
{
while (true)
{
Sample arrivedSample = await this.source.DequeueAsync(); //how should i implement this ?
Console.WriteLine("Just Arrived");
}
}
}正如您在Storage's methodDequeuein aTaskso that i canawaitit in myConsumer. The only reason i usedTaskCompletionSourceis to be able to communicate between theDequeueandEnqueuemethods in theStorage`.类中看到的,我想包装我的Consumer
我不知道是否需要重新初始化tcs,但我想是这样做的,因为在每个Enqueue操作之后,我都想要一个新的Task。
我还在tcs中重新初始化了lock,因为我希望这个特定的实例设置结果。
我该怎么做呢?实现还行吗?System.Reactive会提供更好的选择吗?
https://stackoverflow.com/questions/53968202
复制相似问题