-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBackgroundTaskQueue.cs
More file actions
63 lines (53 loc) · 1.75 KB
/
BackgroundTaskQueue.cs
File metadata and controls
63 lines (53 loc) · 1.75 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace WeChatAdapter;
public class BackgroundTaskQueue : IBackgroundTaskQueue, IDisposable
{
private readonly ConcurrentQueue<Func<CancellationToken, Task>> _workItems = new ConcurrentQueue<Func<CancellationToken, Task>>();
private SemaphoreSlim? _signal = new SemaphoreSlim(0);
/// <summary>
/// Queue a Task to background task queue.
/// </summary>
/// <param name="workItem">The work func need to be queued.</param>
public void QueueBackgroundWorkItem(Func<CancellationToken, Task> workItem)
{
if (workItem == null)
{
throw new ArgumentNullException(nameof(workItem));
}
_workItems.Enqueue(workItem);
_signal!.Release();
}
/// <summary>
/// Dequeue a Task in background task queue.
/// </summary>
/// <param name="token">The work func need to be queued.</param>
/// <returns>A <see cref="Task"/> representing the dequeue operation.</returns>
public async Task<Func<CancellationToken, Task>> DequeueAsync(CancellationToken token)
{
await _signal!.WaitAsync(token).ConfigureAwait(false);
_workItems.TryDequeue(out var workItem);
return workItem!;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (_signal != null)
{
_signal.Dispose();
_signal = null;
}
}
}
}