-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathAsyncQueue.cs
73 lines (61 loc) · 2.01 KB
/
AsyncQueue.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Advanced.Algorithms.Distributed;
/// <summary>
/// A simple asynchronous multi-thread supporting producer/consumer FIFO queue with minimal locking.
/// </summary>
public class AsyncQueue<T>
{
//consumer task queue and lock.
private readonly Queue<TaskCompletionSource<T>> consumerQueue = new();
//data queue.
private readonly Queue<T> queue = new();
private readonly SemaphoreSlim consumerQueueLock = new(1);
public int Count => queue.Count;
/// <summary>
/// Supports multi-threaded producers.
/// Time complexity: O(1).
/// </summary>
public async Task EnqueueAsync(T value, int millisecondsTimeout = int.MaxValue,
CancellationToken taskCancellationToken = default)
{
await consumerQueueLock.WaitAsync(millisecondsTimeout, taskCancellationToken);
if (consumerQueue.Count > 0)
{
var consumer = consumerQueue.Dequeue();
consumer.TrySetResult(value);
}
else
{
queue.Enqueue(value);
}
consumerQueueLock.Release();
}
/// <summary>
/// Supports multi-threaded consumers.
/// Time complexity: O(1).
/// </summary>
public async Task<T> DequeueAsync(int millisecondsTimeout = int.MaxValue,
CancellationToken taskCancellationToken = default)
{
await consumerQueueLock.WaitAsync(millisecondsTimeout, taskCancellationToken);
TaskCompletionSource<T> consumer;
try
{
if (queue.Count > 0)
{
var result = queue.Dequeue();
return result;
}
consumer = new TaskCompletionSource<T>();
taskCancellationToken.Register(() => consumer.TrySetCanceled());
consumerQueue.Enqueue(consumer);
}
finally
{
consumerQueueLock.Release();
}
return await consumer.Task;
}
}