如何使用TaskCompletionSource

时间:2018-12-29 09:07:08

标签: asynchronous .net-core task-parallel-library taskcompletionsource

我遇到的是多生产者和单一消费者的情况。我选择了一个公共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 method出队in a任务so that i can等待it in my消费者. The only reason i used TaskCompletionSource is to be able to communicate between the出队and入队methods in the存储`。

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

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

我应该如何进行呢?可以执行吗? System.Reactive会提供更好的选择吗?

1 个答案:

答案 0 :(得分:1)

我认为您的实现存在一些问题:

  1. 如果您多次致电Enqueue()而没有致电DequeueAsync(),则您将丢失TaskCompletionSource,只有最后一个。然后,在第一次调用后调用DequeueAsync()将不会产生正确的结果。

要解决此问题,您将需要一个TaskCompletionSource的队列。看看here,再看看here

最好,如果队列为空,请使用DequeueAsync中的SemaphoreSlim.WaitAsync()正确等待。

  1. 您也不会保护DequeueAsync()中的队列。