-
Notifications
You must be signed in to change notification settings - Fork 3
/
QueuedHandler.cs
60 lines (52 loc) · 1.41 KB
/
QueuedHandler.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
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace ClassLibrary4
{
public class QueuedHandler<T> : Handles<T> where T : Message
{
private readonly Handles<T> handler;
private readonly ConcurrentQueue<T> queue;
private readonly Thread workerThread;
private volatile bool stop;
public int Count
{
get { return queue.Count; }
}
private void HandleNextMessage(object _)
{
while (false == stop)
{
T message;
if (queue.TryDequeue(out message))
{
handler.Handle(message);
continue;
}
Thread.Sleep(1);
}
}
public QueuedHandler(Handles<T> handler)
{
this.handler = handler;
queue = new ConcurrentQueue<T>();
workerThread = new Thread(HandleNextMessage);
}
public void Handle(T message)
{
queue.Enqueue(message);
}
public void Start()
{
workerThread.Start();
}
public void Stop()
{
stop = true;
}
public override string ToString()
{
return handler + " has " + Count + " items left";
}
}
}