blob: 641bd83ac14b1d50b4b8090d3a6f83c10e722132 (
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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Tango.Core.Threading
{
/// <summary>
/// Represents a message queue dispatcher for delivering messages at a constant interval.
/// </summary>
/// <typeparam name="TMessage"></typeparam>
/// <seealso cref="System.IDisposable" />
public class IntervalMessageDispatcher<TMessage> : IDisposable
{
private Thread _queueThread;
private ProducerConsumerQueue<TMessage> _queue;
private Action<TMessage> _onNext;
private long _framesPushed;
private long _framesDelivered;
/// <summary>
/// Gets or sets the interval.
/// </summary>
public int Interval { get; set; }
/// <summary>
/// Gets or sets the drift compensation interval in milliseconds.
/// Meaning, when frames are pushed in a faster rate than delivery interval.
/// This will trigger a compensation mechanism which will deliver frames faster until it reaches balance
/// Between pushed and delivered frames.
/// </summary>
public int? DriftCompensationInterval { get; set; }
/// <summary>
/// Gets or sets the maximum frames count for drift compensation calculation (default 100).
/// </summary>
public int MaximumFramesForDriftCompensation { get; set; }
/// <summary>
/// Gets or sets the maximum allowed drift before starting to balance 0-1. default 0.1.
/// </summary>
public double MaximumDrift { get; set; }
/// <summary>
/// Gets a value indicating whether this instance has started.
/// </summary>
public bool IsStarted { get; private set; }
/// <summary>
/// Gets the number of queued messages.
/// </summary>
public int Count
{
get { return _queue.Count; }
}
/// <summary>
/// Initializes a new instance of the <see cref="IntervalMessageDispatcher{T}"/> class.
/// </summary>
/// <param name="onNext">The delivery callback.</param>
public IntervalMessageDispatcher(Action<TMessage> onNext)
{
_onNext = onNext;
_queue = new ProducerConsumerQueue<TMessage>();
MaximumDrift = 0.1;
MaximumFramesForDriftCompensation = 100;
}
/// <summary>
/// Starts the dispatching of messages.
/// </summary>
public void Start()
{
if (!IsStarted)
{
_framesPushed = 0;
_framesDelivered = 0;
IsStarted = true;
_queueThread = new Thread(QueueThreadMethod);
_queueThread.Name = "Sequencer Thread";
_queueThread.IsBackground = true;
_queueThread.Start();
}
}
/// <summary>
/// Pushes the specified message.
/// </summary>
/// <param name="message">The message.</param>
public void Push(TMessage message)
{
_framesPushed++;
_queue.BlockEnqueue(message);
}
private void QueueThreadMethod()
{
DateTime lastDriftCompensation = DateTime.Now;
double requiredDriftCompensation = 0;
bool balancing = false;
double balancingFactor = 1;
Stopwatch watch = new Stopwatch();
watch.Start();
while (IsStarted)
{
var item = _queue.BlockDequeue();
if (!IsStarted) break;
watch.Restart();
try
{
_onNext?.Invoke(item);
_framesDelivered++;
}
catch { }
//Compensate drift between pushed frames and delivered frames if any.
if (DriftCompensationInterval.HasValue)
{
if (balancing || (DateTime.Now - lastDriftCompensation).TotalMilliseconds > DriftCompensationInterval)
{
lastDriftCompensation = DateTime.Now;
if (_framesPushed > MaximumFramesForDriftCompensation)
{
var reduction = _framesPushed - MaximumFramesForDriftCompensation;
_framesPushed = MaximumFramesForDriftCompensation;
_framesDelivered = _framesDelivered - reduction;
}
requiredDriftCompensation = (double)(_framesDelivered / _framesPushed);
if (1d - requiredDriftCompensation >= MaximumDrift)
{
balancing = true;
balancingFactor = Math.Max(0, balancingFactor - 0.1);
}
else
{
balancing = false;
balancingFactor = 1;
}
//Debug.WriteLine($"Frames Pushed: {_framesPushed}, Frames Delivered: {_framesDelivered}, Required Compensation: {requiredDriftCompensation}, Balancing: {balancing}, Balancing Factor: {balancingFactor}");
//Debug.WriteLine("Sleep before: " + (int)(Interval - watch.ElapsedMilliseconds));
//Debug.WriteLine("Sleep After: " + (int)((Interval - watch.ElapsedMilliseconds) * requiredDriftCompensation * balancingFactor));
}
}
Thread.Sleep(Math.Max(0, (int)((Interval - watch.ElapsedMilliseconds) * requiredDriftCompensation * balancingFactor)));
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
public void Dispose()
{
IsStarted = false;
}
/// <summary>
/// Creates a new instance of <see cref="IntervalMessageDispatcher{T}"/> and starts it immediately.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="onNext">The on next.</param>
/// <param name="interval">The interval.</param>
/// <returns></returns>
public static IntervalMessageDispatcher<T> StartNew<T>(Action<T> onNext, int interval)
{
IntervalMessageDispatcher<T> dispatcher = new IntervalMessageDispatcher<T>(onNext);
dispatcher.Interval = interval;
dispatcher.Start();
return dispatcher;
}
}
}
|