forked from smiley22/S22.Imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSafeQueue.cs
38 lines (35 loc) · 977 Bytes
/
SafeQueue.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
using System.Collections.Generic;
using System.Threading;
namespace S22.Imap {
/// <summary>
/// A thread-safe Queue.
/// </summary>
internal class SafeQueue<T> {
private readonly Queue<T> _queue = new Queue<T>();
/// <summary>
/// Adds an object to the end of the queue.
/// </summary>
/// <param name="item">The object to add to the queue.</param>
public void Enqueue(T item) {
lock (_queue) {
_queue.Enqueue(item);
if (_queue.Count == 1)
Monitor.PulseAll(_queue);
}
}
/// <summary>
/// Removes and returns the object at the beginning of the queue. If
/// the queue is empty, the method blocks the calling thread until an
/// object is put into the queue by another thread.
/// </summary>
/// <returns>The object that is removed from the beginning
/// of the queue.</returns>
public T Dequeue() {
lock (_queue) {
while (_queue.Count == 0)
Monitor.Wait(_queue);
return _queue.Dequeue();
}
}
}
}