awaitable Task based queue

前端 未结 9 1185
礼貌的吻别
礼貌的吻别 2020-11-27 14:44

I\'m wondering if there exists an implementation/wrapper for ConcurrentQueue, similar to BlockingCollection where taking from the collection does not block, but is instead a

9条回答
  •  一整个雨季
    2020-11-27 15:45

    Well 8 years later I hit this very question and was about to implement the MS AsyncQueue class found in nuget package/namespace: Microsoft.VisualStudio.Threading

    Thanks to @Theodor Zoulias for mentioning this api may be outdated and the DataFlow lib would be a good alternative.

    So I edited my AsyncQueue<> implementation to use BufferBlock<>. Almost the same but works better.

    I use this in an AspNet Core background thread and it runs fully async.

    protected async Task MyRun()
    {
        BufferBlock queue = new BufferBlock();
        Task enqueueTask = StartDataIteration(queue);
    
        while (await queue.OutputAvailableAsync())
        {
            var myObj = queue.Receive();
            // do something with myObj
        }
    
    }
    
    public async Task StartDataIteration(BufferBlock queue)
    {
        var cursor = await RunQuery();
        while(await cursor.Next()) { 
            queue.Post(cursor.Current);
        }
        queue.Complete(); // <<< signals the consumer when queue.Count reaches 0
    }
    

    I found that using the queue.OutputAvailableAsync() fixed the issue that I had with AsyncQueue<> -- trying to determine when the queue was complete and not having to inspect the dequeue task.

提交回复
热议问题