awaitable Task based queue

前端 未结 9 1188
礼貌的吻别
礼貌的吻别 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:34

    Check out https://github.com/somdoron/AsyncCollection, you can both dequeue asynchronously and use C# 8.0 IAsyncEnumerable.

    The API is very similar to BlockingCollection.

    AsyncCollection collection = new AsyncCollection();
    
    var t = Task.Run(async () =>
    {
        while (!collection.IsCompleted)
        {
            var item = await collection.TakeAsync();
    
            // process
        }
    });
    
    for (int i = 0; i < 1000; i++)
    {
        collection.Add(i);
    }
    
    collection.CompleteAdding();
    
    t.Wait();
    

    With IAsyncEnumeable:

    AsyncCollection collection = new AsyncCollection();
    
    var t = Task.Run(async () =>
    {
        await foreach (var item in collection)
        {
            // process
        }
    });
    
    for (int i = 0; i < 1000; i++)
    {
        collection.Add(i);
    }
    
    collection.CompleteAdding();
    
    t.Wait();
    

提交回复
热议问题