47

我想知道是否存在ConcurrentQueue的实现/包装器,类似于BlockingCollection,其中从集合中获取不会阻塞,而是异步的,并且会导致异步等待,直到将项目放入队列中。

我提出了自己的实现,但它似乎没有按预期执行。我想知道我是否正在重新发明已经存在的东西。

这是我的实现:

public class MessageQueue<T>
{
    ConcurrentQueue<T> queue = new ConcurrentQueue<T>();

    ConcurrentQueue<TaskCompletionSource<T>> waitingQueue = 
        new ConcurrentQueue<TaskCompletionSource<T>>();

    object queueSyncLock = new object();

    public void Enqueue(T item)
    {
        queue.Enqueue(item);
        ProcessQueues();
    }

    public async Task<T> Dequeue()
    {
        TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
        waitingQueue.Enqueue(tcs);
        ProcessQueues();
        return tcs.Task.IsCompleted ? tcs.Task.Result : await tcs.Task;
    }

    private void ProcessQueues()
    {
        TaskCompletionSource<T> tcs=null;
        T firstItem=default(T);
        while (true)
        {
            bool ok;
            lock (queueSyncLock)
            {
                ok = waitingQueue.TryPeek(out tcs) && queue.TryPeek(out firstItem);
                if (ok)
                {
                    waitingQueue.TryDequeue(out tcs);
                    queue.TryDequeue(out firstItem);
                }
            }
            if (!ok) break;
            tcs.SetResult(firstItem);
        }
    }
}
4

10 回答 10

68

我不知道无锁解决方案,但您可以查看新的Dataflow library,它是Async CTP的一部分。一个简单的BufferBlock<T>就足够了,例如:

BufferBlock<int> buffer = new BufferBlock<int>();

生产和消费最容易通过数据流块类型的扩展方法完成。

制作很简单:

buffer.Post(13);

并且消费是异步的:

int item = await buffer.ReceiveAsync();

如果可能,我建议您使用 Dataflow;使这样的缓冲区既有效又正确比最初看起来要困难得多。

于 2011-10-23T18:40:08.200 回答
33

使用 C# 8.0IAsyncEnumerableDataflow 库的简单方法

// Instatiate an async queue
var queue = new AsyncQueue<int>();

// Then, loop through the elements of queue.
// This loop won't stop until it is canceled or broken out of
// (for that, use queue.WithCancellation(..) or break;)
await foreach(int i in queue) {
    // Writes a line as soon as some other Task calls queue.Enqueue(..)
    Console.WriteLine(i);
}

实现AsyncQueue如下:

public class AsyncQueue<T> : IAsyncEnumerable<T>
{
    private readonly SemaphoreSlim _enumerationSemaphore = new SemaphoreSlim(1);
    private readonly BufferBlock<T> _bufferBlock = new BufferBlock<T>();

    public void Enqueue(T item) =>
        _bufferBlock.Post(item);

    public async IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken token = default)
    {
        // We lock this so we only ever enumerate once at a time.
        // That way we ensure all items are returned in a continuous
        // fashion with no 'holes' in the data when two foreach compete.
        await _enumerationSemaphore.WaitAsync();
        try {
            // Return new elements until cancellationToken is triggered.
            while (true) {
                // Make sure to throw on cancellation so the Task will transfer into a canceled state
                token.ThrowIfCancellationRequested();
                yield return await _bufferBlock.ReceiveAsync(token);
            }
        } finally {
            _enumerationSemaphore.Release();
        }

    }
}
于 2019-04-30T01:18:38.810 回答
13

现在有一种官方方法可以做到这一点:System.Threading.Channels. 它内置于 .NET Core 3.0 及更高版本(包括 .NET 5.0 和 6.0)的核心运行时中,但也可作为 .NET Standard 2.0 和 2.1 上的 NuGet 包使用。您可以在此处阅读文档。

var channel = System.Threading.Channels.Channel.CreateUnbounded<int>();

排队工作:

// This will succeed and finish synchronously if the channel is unbounded.
channel.Writer.TryWrite(42);

完成频道:

channel.Writer.TryComplete();

从频道读取:

var i = await channel.Reader.ReadAsync();

或者,如果您有 .NET Core 3.0 或更高版本:

await foreach (int i in channel.Reader.ReadAllAsync())
{
    // whatever processing on i...
}
于 2021-04-09T18:40:22.853 回答
7

实现这一点的一种简单易行的方法是使用SemaphoreSlim

public class AwaitableQueue<T>
{
    private SemaphoreSlim semaphore = new SemaphoreSlim(0);
    private readonly object queueLock = new object();
    private Queue<T> queue = new Queue<T>();

    public void Enqueue(T item)
    {
        lock (queueLock)
        {
            queue.Enqueue(item);
            semaphore.Release();
        }
    }

    public T WaitAndDequeue(TimeSpan timeSpan, CancellationToken cancellationToken)
    {
        semaphore.Wait(timeSpan, cancellationToken);
        lock (queueLock)
        {
            return queue.Dequeue();
        }
    }

    public async Task<T> WhenDequeue(TimeSpan timeSpan, CancellationToken cancellationToken)
    {
        await semaphore.WaitAsync(timeSpan, cancellationToken);
        lock (queueLock)
        {
            return queue.Dequeue();
        }
    }
}

这样做的美妙之处在于它处理了实现和功能SemaphoreSlim的所有复杂性。缺点是队列长度由信号量队列本身跟踪,并且它们都神奇地保持同步。Wait()WaitAsync()

于 2020-01-09T03:50:45.857 回答
5

我的尝试(它在创建“承诺”时引发了一个事件,外部生产者可以使用它来了解何时生产更多项目):

public class AsyncQueue<T>
{
    private ConcurrentQueue<T> _bufferQueue;
    private ConcurrentQueue<TaskCompletionSource<T>> _promisesQueue;
    private object _syncRoot = new object();

    public AsyncQueue()
    {
        _bufferQueue = new ConcurrentQueue<T>();
        _promisesQueue = new ConcurrentQueue<TaskCompletionSource<T>>();
    }

    /// <summary>
    /// Enqueues the specified item.
    /// </summary>
    /// <param name="item">The item.</param>
    public void Enqueue(T item)
    {
        TaskCompletionSource<T> promise;
        do
        {
            if (_promisesQueue.TryDequeue(out promise) &&
                !promise.Task.IsCanceled &&
                promise.TrySetResult(item))
            {
                return;                                       
            }
        }
        while (promise != null);

        lock (_syncRoot)
        {
            if (_promisesQueue.TryDequeue(out promise) &&
                !promise.Task.IsCanceled &&
                promise.TrySetResult(item))
            {
                return;
            }

            _bufferQueue.Enqueue(item);
        }            
    }

    /// <summary>
    /// Dequeues the asynchronous.
    /// </summary>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns></returns>
    public Task<T> DequeueAsync(CancellationToken cancellationToken)
    {
        T item;

        if (!_bufferQueue.TryDequeue(out item))
        {
            lock (_syncRoot)
            {
                if (!_bufferQueue.TryDequeue(out item))
                {
                    var promise = new TaskCompletionSource<T>();
                    cancellationToken.Register(() => promise.TrySetCanceled());

                    _promisesQueue.Enqueue(promise);
                    this.PromiseAdded.RaiseEvent(this, EventArgs.Empty);

                    return promise.Task;
                }
            }
        }

        return Task.FromResult(item);
    }

    /// <summary>
    /// Gets a value indicating whether this instance has promises.
    /// </summary>
    /// <value>
    /// <c>true</c> if this instance has promises; otherwise, <c>false</c>.
    /// </value>
    public bool HasPromises
    {
        get { return _promisesQueue.Where(p => !p.Task.IsCanceled).Count() > 0; }
    }

    /// <summary>
    /// Occurs when a new promise
    /// is generated by the queue
    /// </summary>
    public event EventHandler PromiseAdded;
}
于 2014-04-08T13:19:30.160 回答
1

对于您的用例来说,这可能有点矫枉过正(考虑到学习曲线),但反应式扩展提供了您可能想要的异步组合的所有粘合剂。

您基本上订阅了更改,它们会在可用时推送给您,您可以让系统将更改推送到单独的线程上。

于 2011-10-23T00:48:09.483 回答
1

查看https://github.com/somdoron/AsyncCollection,您既可以异步出队,也可以使用 C# 8.0 IAsyncEnumerable。

该 API 与 BlockingCollection 非常相似。

AsyncCollection<int> collection = new AsyncCollection<int>();

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();

使用 IAsyncEnumable:

AsyncCollection<int> collection = new AsyncCollection<int>();

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();
于 2019-07-07T09:49:06.280 回答
0

这是我目前正在使用的实现。

public class MessageQueue<T>
{
    ConcurrentQueue<T> queue = new ConcurrentQueue<T>();
    ConcurrentQueue<TaskCompletionSource<T>> waitingQueue = 
        new ConcurrentQueue<TaskCompletionSource<T>>();
    object queueSyncLock = new object();
    public void Enqueue(T item)
    {
        queue.Enqueue(item);
        ProcessQueues();
    }

    public async Task<T> DequeueAsync(CancellationToken ct)
    {
        TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
        ct.Register(() =>
        {
            lock (queueSyncLock)
            {
                tcs.TrySetCanceled();
            }
        });
        waitingQueue.Enqueue(tcs);
        ProcessQueues();
        return tcs.Task.IsCompleted ? tcs.Task.Result : await tcs.Task;
    }

    private void ProcessQueues()
    {
        TaskCompletionSource<T> tcs = null;
        T firstItem = default(T);
        lock (queueSyncLock)
        {
            while (true)
            {
                if (waitingQueue.TryPeek(out tcs) && queue.TryPeek(out firstItem))
                {
                    waitingQueue.TryDequeue(out tcs);
                    if (tcs.Task.IsCanceled)
                    {
                        continue;
                    }
                    queue.TryDequeue(out firstItem);
                }
                else
                {
                    break;
                }
                tcs.SetResult(firstItem);
            }
        }
    }
}

它工作得很好,但是在 上存在很多争论queueSyncLock,因为我经常使用CancellationToken来取消一些等待的任务。当然,这会导致我看到的阻塞大大减少,BlockingCollection但是......

我想知道是否有一种更流畅、无锁的方法来达到同样的目的

于 2011-10-23T13:59:50.763 回答
0

8 年后,我遇到了这个问题,即将实现AsyncQueue<T>在 nuget 包/命名空间中找到的 MS 类:Microsoft.VisualStudio.Threading

感谢@Theodor Zoulias 提到这个 api 可能已经过时,DataFlow 库将是一个不错的选择。

所以我编辑了我的 AsyncQueue<> 实现以使用 BufferBlock<>。几乎相同,但效果更好。

我在 AspNet Core 后台线程中使用它,它完全异步运行。

protected async Task MyRun()
{
    BufferBlock<MyObj> queue = new BufferBlock<MyObj>();
    Task enqueueTask = StartDataIteration(queue);

    while (await queue.OutputAvailableAsync())
    {
        var myObj = queue.Receive();
        // do something with myObj
    }

}

public async Task StartDataIteration(BufferBlock<MyObj> queue)
{
    var cursor = await RunQuery();
    while(await cursor.Next()) { 
        queue.Post(cursor.Current);
    }
    queue.Complete(); // <<< signals the consumer when queue.Count reaches 0
}

我发现使用 queue.OutputAvailableAsync() 解决了我在使用 AsyncQueue<> 时遇到的问题——尝试确定队列何时完成而不必检查出队任务。

于 2020-03-10T14:41:56.557 回答
-5

您可以只使用 a BlockingCollection(使用默认值ConcurrentQueue)并将调用包装Take在 a 中Task,这样您就可以await了:

var bc = new BlockingCollection<T>();

T element = await Task.Run( () => bc.Take() );
于 2011-10-23T09:56:22.877 回答