forked from geloczi/synologydotnet-audiostation-wpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueProcessorTasks.cs
84 lines (73 loc) · 2.52 KB
/
QueueProcessorTasks.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
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Utils
{
public class QueueProcessorTasks<T>
{
private readonly Func<CancellationToken, T, Task> _action;
private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
private readonly List<Task> _tasks = new List<Task>();
private readonly CancellationToken _token;
private bool _finishedAdding;
public bool Cancelled => _token.IsCancellationRequested;
public QueueProcessorTasks(Func<CancellationToken, T, Task> action) : this(action, Environment.ProcessorCount)
{
}
public QueueProcessorTasks(Func<CancellationToken, T, Task> action, int numberOfParallelTasks)
{
if (action is null)
throw new ArgumentNullException(nameof(action));
if (numberOfParallelTasks <= 0)
throw new ArgumentOutOfRangeException(nameof(numberOfParallelTasks));
_action = action;
_token = _tokenSource.Token;
for (int i = 0; i < numberOfParallelTasks; i++)
_tasks.Add(Task.Run(WorkMethod));
}
private async Task WorkMethod()
{
while (!_token.IsCancellationRequested)
{
if (_queue.TryDequeue(out var item))
await _action(_token, item);
else if (_finishedAdding)
break;
else
await Task.Delay(10);
}
}
public void Enqueue(T item)
{
if (_finishedAdding)
throw new InvalidOperationException("Adding new items is not possible after the Wait method invoked");
if (_token.IsCancellationRequested)
throw new TaskCanceledException();
_queue.Enqueue(item);
}
public void FinishedAdding()
{
_finishedAdding = true;
}
public void Wait()
{
_finishedAdding = true;
foreach (var t in _tasks)
t.Wait();
}
public async Task WaitAsync()
{
_finishedAdding = true;
foreach (var t in _tasks)
await t;
}
public void Cancel()
{
if (!Cancelled)
_tokenSource.Cancel();
}
}
}