C#C
C#10mo ago
nathanAjacobs

Would this AsyncQueue have issues with multiple producers and a single consumer?

First, I know Channels exist and I would obviously use them instead.

I can't use them because I'm adding functionality to an existing Unity library that does not have access to them. I'm intending to use this internally in the library for IPC purposes between Unity Editor instances.

Will this implementation have issues with synchronization? Also will FIFO be preserved?

I think the answer is there are no issues with this, but want to confirm.

internal class AsyncQueue<T>
{
    private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);

    public void Enqueue(T item)
    {
        _queue.Enqueue(item);
        _semaphore.Release();
    }

    public async Task<T> DequeueAsync()
    {
        await _semaphore.WaitAsync().ConfigureAwait(false);
        if (_queue.TryDequeue(out T item))
        {
            return item;
        }

        throw new InvalidOperationException("Something went wrong, there is nothing to dequeue.");
    }
}
Was this page helpful?