Skip to content

Instantly share code, notes, and snippets.

@neoGeneva
Created August 14, 2021 08:51
Show Gist options
  • Save neoGeneva/91445bfa496932927899f0dd2c1f12bd to your computer and use it in GitHub Desktop.
Save neoGeneva/91445bfa496932927899f0dd2c1f12bd to your computer and use it in GitHub Desktop.
class UberQueue<T>
{
private IAsyncQueue<T>[] _queues;
private Task<T>[] _tasks;
public UberQueue(IAsyncQueue<T>[] queues)
{
_queues = queues;
}
async Task<T> DequeueAsync()
{
_tasks ??= _queues
.Select(x => x.DequeueAsync())
.ToArray();
await Task.WhenAny(_tasks);
for (var i = 0; i < _tasks.Length; i++)
{
if (_tasks[i].IsCompleted)
{
var result = _tasks[i].Result;
_tasks[i] = _queues[i].DequeueAsync();
return result;
}
}
throw new InvalidOperationException("No tasks are completed");
}
}
interface IAsyncQueue<T>
{
Task<T> DequeueAsync();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment