Skip to content

Instantly share code, notes, and snippets.

@Vake93
Created August 14, 2021 10:18
Show Gist options
  • Save Vake93/96e0c78e6eb02384c420a26592f2881f to your computer and use it in GitHub Desktop.
Save Vake93/96e0c78e6eb02384c420a26592f2881f to your computer and use it in GitHub Desktop.
UberQueue
class UberQueue<T>
{
private readonly SemaphoreSlim _semaphore;
private readonly IAsyncQueue<T>[] _queues;
public UberQueue(IAsyncQueue<T>[] queues)
{
_semaphore = new SemaphoreSlim(1, 1);
_queues = queues;
}
private Task<T>[]? PendingTasks { get; set; }
public async Task<T> DequeueAsync()
{
try
{
await _semaphore.WaitAsync();
if (PendingTasks == null || PendingTasks.Length == 0)
{
PendingTasks = _queues.Select(q => q.DequeueAsync()).ToArray();
}
var completedTask = await Task.WhenAny(PendingTasks);
PendingTasks = PendingTasks.Where(t => t != completedTask).ToArray();
return await completedTask;
}
finally
{
_semaphore.Release();
}
}
}
interface IAsyncQueue<T>
{
Task<T> DequeueAsync();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment