@@ -9,42 +9,38 @@ namespace JsonRpc
9
9
{
10
10
public class OutputHandler : IOutputHandler
11
11
{
12
- private readonly TimeSpan _sleepTime = TimeSpan . FromMilliseconds ( 50 ) ;
13
12
private readonly TextWriter _output ;
14
13
private Thread _thread ;
15
- private readonly ConcurrentQueue < object > _queue ;
14
+ private readonly BlockingCollection < object > _queue ;
15
+ private readonly CancellationTokenSource _cancel ;
16
16
17
17
public OutputHandler ( TextWriter output )
18
18
{
19
19
_output = output ;
20
- _queue = new ConcurrentQueue < object > ( ) ;
20
+ _queue = new BlockingCollection < object > ( ) ;
21
+ _cancel = new CancellationTokenSource ( ) ;
21
22
_thread = new Thread ( ProcessOutputQueue ) {
22
23
IsBackground = true
23
24
} ;
24
25
}
25
26
26
- internal OutputHandler ( TextWriter output , TimeSpan sleepTime )
27
- : this ( output )
28
- {
29
- _sleepTime = sleepTime ;
30
- }
31
-
32
27
public void Start ( )
33
28
{
34
29
_thread . Start ( ) ;
35
30
}
36
31
37
32
public void Send ( object value )
38
33
{
39
- _queue . Enqueue ( value ) ;
34
+ _queue . Add ( value ) ;
40
35
}
36
+
41
37
private void ProcessOutputQueue ( )
42
38
{
39
+ var token = _cancel . Token ;
43
40
while ( true )
44
41
{
45
42
if ( _thread == null ) return ;
46
-
47
- if ( _queue . TryDequeue ( out var value ) )
43
+ if ( _queue . TryTake ( out var value , - 1 , token ) )
48
44
{
49
45
var content = JsonConvert . SerializeObject ( value ) ;
50
46
@@ -56,18 +52,14 @@ private void ProcessOutputQueue()
56
52
57
53
_output . Write ( sb . ToString ( ) ) ;
58
54
}
59
-
60
- if ( _queue . IsEmpty )
61
- {
62
- Thread . Sleep ( _sleepTime ) ;
63
- }
64
55
}
65
56
}
66
57
67
58
public void Dispose ( )
68
59
{
69
60
_output ? . Dispose ( ) ;
70
61
_thread = null ;
62
+ _cancel . Cancel ( ) ;
71
63
}
72
64
}
73
65
}
0 commit comments