-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathResultQueue.cs
93 lines (83 loc) · 2.34 KB
/
ResultQueue.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Net.DDP.Server;
using Net.DDP.Server.Interfaces;
namespace Net.DDP.Server
{
internal class ResultQueue<T>
{
private readonly ManualResetEvent _enqueuedEvent;
private readonly IProcessQueues<T> _queueProcessor;
private readonly Queue<T> _itemQueue;
private Thread _workerThread;
private T _currentItem;
public ResultQueue(IProcessQueues<T> queueProcessor)
{
_itemQueue = new Queue<T>();
_queueProcessor = queueProcessor;
_enqueuedEvent = new ManualResetEvent(false);
_workerThread = new Thread(DequeueItem);
_workerThread.Start();
}
/// <summary>
/// Adds an item to the queue for processing
/// </summary>
/// <param name="item"></param>
public void AddItem(T item)
{
lock (_itemQueue)
{
_itemQueue.Enqueue(item);
_enqueuedEvent.Set();
}
RestartThread();
}
/// <summary>
/// Processes an item from the queue
/// </summary>
/// <returns></returns>
private bool Dequeue()
{
lock (_itemQueue)
{
if (_itemQueue.Count > 0)
{
_enqueuedEvent.Reset();
_currentItem = _itemQueue.Dequeue();
}
else
{
return false;
}
return true;
}
}
/// <summary>
/// Restarts the thread used to dequeue items
/// </summary>
public void RestartThread()
{
if (_workerThread.ThreadState == ThreadState.Stopped)
{
_workerThread.Abort();
_workerThread = new Thread(DequeueItem);
_workerThread.Start();
}
}
/// <summary>
/// Processes an item from the queue
/// </summary>
/// <returns></returns>
private void DequeueItem()
{
while (Dequeue())
{
_queueProcessor.ProcessItem(_currentItem);
}
}
}
}