-
Notifications
You must be signed in to change notification settings - Fork 51
/
BatchNotification.cs
147 lines (124 loc) · 4.67 KB
/
BatchNotification.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// https://github.com/aspnet/logging/blob/dev/src/Microsoft.Extensions.Logging.AzureAppServices/Internal/BatchingLoggerProvider.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace DevelopmentInProgress.TradeServer.StrategyExecution.WebHost.Notification
{
public abstract class BatchNotification<T> : IBatchNotification<T>, IDisposable
{
private readonly List<T> currentBatch = new List<T>();
private BlockingCollection<T> notifyQueue;
private Task outputTask;
private CancellationTokenSource cancellationTokenSource;
private bool disposed;
protected TimeSpan Interval { get; set; } = new TimeSpan(0, 0, 0, 1);
protected int? QueueSize { get; set; }
protected int? BatchSize { get; set; }
public abstract Task NotifyAsync(IEnumerable<T> items, CancellationToken cancellationToken);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types")]
public void AddNotification(T item)
{
if (!notifyQueue.IsAddingCompleted)
{
try
{
notifyQueue.Add(item, cancellationTokenSource.Token);
}
catch
{
//cancellation token cancelled or CompleteAdding called
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
internal void Stop()
{
cancellationTokenSource.Cancel();
notifyQueue.CompleteAdding();
try
{
outputTask.Wait(Interval);
}
catch (TaskCanceledException)
{
}
catch (AggregateException ex) when (ex.InnerExceptions.Count == 1 && ex.InnerExceptions[0] is TaskCanceledException)
{
}
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
cancellationTokenSource.Cancel();
cancellationTokenSource.Dispose();
}
disposed = true;
}
protected void Start()
{
if (BatchSize.HasValue
&& BatchSize <= 0)
{
throw new ArgumentOutOfRangeException("BatchSize", "BatchSize must be a positive number.");
}
if (QueueSize.HasValue
&& QueueSize <= 0)
{
throw new ArgumentOutOfRangeException("QueueSize", "QueueSize must be a positive number.");
}
if (Interval <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException("Interval", "Interval must be longer than zero.");
}
notifyQueue = QueueSize == null ?
new BlockingCollection<T>(new ConcurrentQueue<T>()) :
new BlockingCollection<T>(new ConcurrentQueue<T>(), QueueSize.Value);
cancellationTokenSource = new CancellationTokenSource();
outputTask = Task.Factory.StartNew<Task>(
ProcessNotificationQueue,
null, cancellationTokenSource.Token,
TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types")]
private async Task ProcessNotificationQueue(object state)
{
while (!cancellationTokenSource.IsCancellationRequested)
{
var limit = BatchSize ?? int.MaxValue;
while (limit > 0 && notifyQueue.TryTake(out var notification))
{
currentBatch.Add(notification);
limit--;
}
if (currentBatch.Count > 0)
{
try
{
await NotifyAsync(currentBatch, cancellationTokenSource.Token).ConfigureAwait(false);
}
catch
{
// ignored
}
currentBatch.Clear();
}
await IntervalAsync(Interval, cancellationTokenSource.Token).ConfigureAwait(false);
}
}
private static Task IntervalAsync(TimeSpan interval, CancellationToken cancellationToken)
{
return Task.Delay(interval, cancellationToken);
}
}
}