/
QueueLogRunner.cs
68 lines (55 loc) · 2.13 KB
/
QueueLogRunner.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
using System;
using System.IO;
using ModuleManager.Collections;
namespace ModuleManager.Logging
{
public class QueueLogRunner
{
private enum State
{
Initialized,
Running,
StopRequested,
Stopped,
}
private State state = State.Initialized;
private readonly IMessageQueue<ILogMessage> logQueue;
private readonly long timeToWaitForLogsMs;
public QueueLogRunner(IMessageQueue<ILogMessage> logQueue, long timeToWaitForLogsMs = 50)
{
this.logQueue = logQueue ?? throw new ArgumentNullException(nameof(logQueue));
if (timeToWaitForLogsMs < 0) throw new ArgumentException("must be non-negative", nameof(timeToWaitForLogsMs));
this.timeToWaitForLogsMs = timeToWaitForLogsMs;
}
public void RequestStop()
{
if (state == State.StopRequested || state == State.Stopped) return;
if (state != State.Running) throw new InvalidOperationException($"Cannot request stop from {state} state");
state = State.StopRequested;
}
public void Run(IBasicLogger logger)
{
if (state != State.Initialized) throw new InvalidOperationException($"Cannot run from {state} state");
if (logger == null) throw new ArgumentNullException(nameof(logger));
state = State.Running;
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
while (state == State.Running)
{
stopwatch.Start();
foreach (ILogMessage message in logQueue.TakeAll())
{
logger.Log(message);
}
long timeRemaining = timeToWaitForLogsMs - stopwatch.ElapsedMilliseconds;
if (timeRemaining > 0)
System.Threading.Thread.Sleep((int)timeRemaining);
stopwatch.Reset();
}
foreach (ILogMessage message in logQueue.TakeAll())
{
logger.Log(message);
}
state = State.Stopped;
}
}
}