0

我遇到了多生产者和单一消费者的情况。我选择了一个公共thread-safe资源,其中所有生产者Enqueue项目。但是,当使用该资源时,我不知道如何有效地制作await新项目的生产者。Dequeue

POCO

struct Sample
    {
        public int Id { get; set; }
        public  double Value { get; set; }
    }

生产者

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;
        }
    }

消费者

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");
            }
        }
    }

正如您在Consumer课堂上看到的那样,我想包装我的Storage's methodDequeue in aTask so that i canawait it in myConsumer . The only reason i usedTaskCompletionSource is to be able to communicate between theDequeue andEnqueue methods in theStorage`。

我不知道我是否需要重新初始化,tcs但我想我这样做是因为我Task在每次Enqueue操作后都想要一个新的。

我还重新初始化了tcs内部,lock因为我希望该特定实例设置结果。

我应该如何处理这个?实施好吗?会System.Reactive提供更好的选择吗?

4

1 回答 1

1

我想我看到您的实施存在几个问题:

  1. 如果您Enqueue()多次调用而不调用DequeueAsync(),您将失去TaskCompletionSource并且只有最后一个。然后,DequeueAsync()第一次调用后调用不会产生正确的结果。

要解决此问题,您将需要一个TaskCompletionSource's 队列。看看这里,再看看这里

更好的是,如果队列为空,请使用SemaphoreSlim.WaitAsync() inDequeueAsync正确等待。

  1. 你也不保护你的队列DequeueAsync()
于 2018-12-30T10:39:39.760 回答