-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConcurrentCollectionDecorator.cs
More file actions
101 lines (64 loc) · 2.3 KB
/
ConcurrentCollectionDecorator.cs
File metadata and controls
101 lines (64 loc) · 2.3 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
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
93
94
95
96
97
98
99
100
101
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Gsemac.Collections {
public sealed class ConcurrentCollectionDecorator<T> :
ICollection<T> {
// Public members
public int Count {
get {
lock (mutex)
return underlyingCollection.Count;
}
}
public bool IsReadOnly {
get {
lock (mutex)
return underlyingCollection.IsReadOnly;
}
}
public ConcurrentCollectionDecorator(ICollection<T> underlyingCollection) :
this(underlyingCollection, mutex: new object()) {
}
public ConcurrentCollectionDecorator(ICollection<T> underlyingCollection, object mutex) {
if (underlyingCollection is null)
throw new ArgumentNullException(nameof(underlyingCollection));
if (mutex is null)
throw new ArgumentNullException(nameof(mutex));
this.underlyingCollection = underlyingCollection;
this.mutex = mutex;
}
public void Add(T item) {
lock (mutex)
underlyingCollection.Add(item);
}
public bool Contains(T item) {
lock (mutex)
return underlyingCollection.Contains(item);
}
public bool Remove(T item) {
lock (mutex)
return underlyingCollection.Remove(item);
}
public void Clear() {
lock (mutex)
underlyingCollection.Clear();
}
public void CopyTo(T[] array, int arrayIndex) {
lock (mutex)
underlyingCollection.CopyTo(array, arrayIndex);
}
public IEnumerator<T> GetEnumerator() {
// Return an enumerator for a "frozen" copy of the collection to avoid the possibly of it being modified while iterating.
lock (mutex)
return ((IEnumerable<T>)underlyingCollection.ToArray()).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
// Private members
private readonly ICollection<T> underlyingCollection;
private readonly object mutex;
}
}