-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConcurrentSortedQueue.cs
More file actions
66 lines (60 loc) · 1.62 KB
/
ConcurrentSortedQueue.cs
File metadata and controls
66 lines (60 loc) · 1.62 KB
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
using System;
using System.Collections.Generic;
namespace LightNet
{
/// <summary>
/// This is a thread safe sorted queue.
/// Enqueued elements will be sorted into their approprivate place immediately using their key.
/// </summary>
public class ConcurrentSortedQueue<TKey, TValue> where TKey : struct where TValue : class
{
SortedList<TKey, TValue> List = new SortedList<TKey, TValue>();
readonly object Lock = new object();
public bool Enqueue(TKey key, TValue value)
{
lock (Lock)
{
try
{
List.Add(key, value);
return true;
}
catch (ArgumentException)
{
LogQueue.LogError("Cannot add element ({}, {}) to list, key already exists!", new object[]{ key, value });
return false;
}
}
}
public bool TryDequeue(out TValue value)
{
lock (Lock)
{
if (List.Values.Count == 0)
{
value = null;
return false;
}
value = List.Values[0];
List.RemoveAt(0);
}
return true;
}
public void Clear()
{
lock (Lock)
{
List.Clear();
}
}
public int GetCount()
{
int count;
lock (Lock)
{
count = List.Count;
}
return count;
}
}
}