blob: 8d5adf204ea2fb65ba702fb84c00491f10706fe7 (
plain)
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
|
namespace HyperBooru.Util;
public class LimitedConcurrencyTaskScheduler : TaskScheduler {
public sealed override int MaximumConcurrencyLevel =>
maxConcurrency;
private int maxConcurrency;
[ThreadStatic]
private static bool threadIsProcessingItems;
private readonly LinkedList<Task> tasks = new();
private int delegatesQueuedOrRunning = 0;
public LimitedConcurrencyTaskScheduler() {
maxConcurrency = Environment.ProcessorCount;
}
public LimitedConcurrencyTaskScheduler(int maxConcurrency) {
if(maxConcurrency < 1)
throw new ArgumentOutOfRangeException("maxConcurrency must be greater than 0");
this.maxConcurrency = (int) maxConcurrency;
}
protected sealed override void QueueTask(Task task) {
lock(tasks) {
tasks.AddLast(task);
if(delegatesQueuedOrRunning < maxConcurrency) {
delegatesQueuedOrRunning++;
NotifyThreadPoolOfPendingWork();
}
}
}
private void NotifyThreadPoolOfPendingWork() {
ThreadPool.UnsafeQueueUserWorkItem(_ => {
threadIsProcessingItems = true;
try {
while(true) {
Task item;
lock(tasks) {
if(tasks.Count == 0) {
delegatesQueuedOrRunning--;
break;
} else {
item = tasks.First.Value;
tasks.RemoveFirst();
}
}
TryExecuteTask(item);
}
} finally {
threadIsProcessingItems = false;
}
}, null);
}
protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) {
if(!threadIsProcessingItems)
return false;
if(taskWasPreviouslyQueued)
return TryDequeue(task) ? TryExecuteTask(task) : false;
else
return TryExecuteTask(task);
}
protected sealed override bool TryDequeue(Task task) {
lock(tasks) {
return tasks.Remove(task);
}
}
protected sealed override IEnumerable<Task> GetScheduledTasks() {
bool lockTaken = false;
try {
Monitor.TryEnter(tasks, ref lockTaken);
if(lockTaken)
return tasks;
else
throw new NotSupportedException();
} finally {
if(lockTaken)
Monitor.Exit(tasks);
}
}
}
|