-
Notifications
You must be signed in to change notification settings - Fork 44
/
TraceListenerQueue.cs
103 lines (91 loc) · 3.17 KB
/
TraceListenerQueue.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
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Reqnroll.Tracing
{
public class TraceListenerQueue : ITraceListenerQueue
{
private readonly ITestRunnerManager _testRunnerManager;
private readonly ITraceListener _traceListener;
private readonly bool _isThreadSafeTraceListener;
private BlockingCollection<TraceMessage> _messages;
private Task _consumerTask;
private Exception _error;
public TraceListenerQueue(ITraceListener traceListener, ITestRunnerManager testRunnerManager)
{
_traceListener = traceListener;
_testRunnerManager = testRunnerManager;
_isThreadSafeTraceListener = traceListener is IThreadSafeTraceListener;
}
public void Start()
{
_messages = new BlockingCollection<TraceMessage>();
_consumerTask = Task.Factory.StartNew(() =>
{
try
{
while (true)
{
var message = _messages.Take();
ForwardMessage(message);
}
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
_error = ex;
}
},
// We don't want to block an thread of the pool for the whole duration, so create a new Thread for it
TaskCreationOptions.LongRunning);
}
public void EnqueueMessage(ITestRunner sourceTestRunner, string message, bool isToolMessgae)
{
if (_error != null)
throw new ReqnrollException("Trace listener failed.", _error);
if (_isThreadSafeTraceListener || !_testRunnerManager.IsMultiThreaded)
{
// log synchronously
ForwardMessage(new TraceMessage(isToolMessgae, message));
return;
}
if (_consumerTask == null)
{
lock (this)
{
if (_consumerTask == null)
Start();
}
}
_messages.Add(new TraceMessage(isToolMessgae, string.Format("#{1}: {0}", message, sourceTestRunner.TestWorkerId)));
}
public void Dispose()
{
if (_consumerTask != null)
{
_messages.CompleteAdding();
_consumerTask.Wait();
_consumerTask = null;
}
}
private void ForwardMessage(TraceMessage message)
{
if (message.IsToolMessage)
_traceListener.WriteToolOutput(message.Message);
else
_traceListener.WriteTestOutput(message.Message);
}
private readonly struct TraceMessage
{
public bool IsToolMessage { get; }
public string Message { get; }
public TraceMessage(bool isToolMessage, string message) : this()
{
IsToolMessage = isToolMessage;
Message = message;
}
}
}
}