forked from smiley22/S22.Imap
-
Notifications
You must be signed in to change notification settings - Fork 1
/
SafeQueue.cs
36 lines (33 loc) · 958 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
using System.Collections.Generic;
using System.Threading;
namespace S22.Imap {
/// <summary>
/// A thread-safe Queue.
/// </summary>
internal class SafeQueue<T> {
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 was removed from the beginning of the queue.</returns>
public T Dequeue() {
lock (_queue) {
while (_queue.Count == 0)
Monitor.Wait(_queue);
return _queue.Dequeue();
}
}
}
}