-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChannelService.cs
More file actions
93 lines (84 loc) · 2.61 KB
/
Copy pathChannelService.cs
File metadata and controls
93 lines (84 loc) · 2.61 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System.Text;
public static class ChannelService
{
private static Dictionary<string, List<TaskCompletionSource<(string, byte[])>>> _awaitingQueues = new();
private static Dictionary<string, Queue<(string, byte[])>> _bufferQueues = new();
private static List<TaskCompletionSource<(string, byte[])>> GetAwaitingQueue(string channelId)
{
List<TaskCompletionSource<(string, byte[])>>? queue;
lock (_awaitingQueues)
{
if (!_awaitingQueues.TryGetValue(channelId, out queue))
{
queue = new List<TaskCompletionSource<(string, byte[])>>();
_awaitingQueues.Add(channelId, queue);
}
}
return queue;
}
private static Queue<(string, byte[])> GetBufferQueue(string channelId)
{
Queue<(string, byte[])>? queue;
lock (_bufferQueues)
{
if (!_bufferQueues.TryGetValue(channelId, out queue))
{
queue = new ();
_bufferQueues.Add(channelId, queue);
}
}
return queue;
}
public static async Task<(string, byte[])> ReadData(string channelId, CancellationToken cancellationToken)
{
var bufferQueue = GetBufferQueue(channelId);
lock (bufferQueue)
{
if (bufferQueue.Count > 0)
{
return bufferQueue.Dequeue();
}
}
var source = new TaskCompletionSource<(string, byte[])>();
var awaitingQueue = GetAwaitingQueue(channelId);
lock (awaitingQueue)
{
awaitingQueue.Add(source);
}
cancellationToken.Register(() => {
source.SetCanceled();
awaitingQueue.Remove(source);
});
try
{
return await source.Task;;
}
catch(Exception)
{
return ("text/plain", Encoding.UTF8.GetBytes("canceled"));
}
}
public static async Task WriteData(string channelId, string contentType, byte[] data)
{
TaskCompletionSource<(string, byte[])> source = null;
var awaitingQueue = GetAwaitingQueue(channelId);
lock (awaitingQueue)
{
if (awaitingQueue.Count > 0)
{
source = awaitingQueue[0];
awaitingQueue.RemoveAt(0);
}
}
if (source != null)
{
source.SetResult((contentType, data));
return;
}
var bufferQueue = GetBufferQueue(channelId);
lock (bufferQueue)
{
bufferQueue.Enqueue((contentType, data));
}
}
}