152
|
1 using System;
|
|
2 using System.Collections.Generic;
|
|
3 using System.Linq;
|
|
4
|
|
5 namespace Implab.Components {
|
|
6 /// <summary>
|
|
7 /// Component container.
|
|
8 /// </summary>
|
|
9 /// <remarks>Instanses of this class are thread safe.</remarks>
|
|
10 public class ComponentContainer<T> : Disposable, ICollection<T> {
|
|
11 readonly HashSet<T> m_components = new HashSet<T>();
|
|
12
|
|
13 public void Clear() {
|
|
14 T[] removed;
|
|
15
|
|
16 lock (m_components) {
|
|
17 removed = new T[m_components.Count];
|
|
18 m_components.CopyTo(removed);
|
|
19 m_components.Clear();
|
|
20 }
|
|
21
|
|
22 foreach (var item in removed.OfType<IDisposable>())
|
|
23 item.Dispose();
|
|
24 }
|
|
25
|
|
26 public bool Contains(T item) {
|
|
27 lock (m_components)
|
|
28 return m_components.Contains(item);
|
|
29 }
|
|
30
|
|
31 public void CopyTo(T[] array, int arrayIndex) {
|
|
32 lock (m_components)
|
|
33 m_components.CopyTo(array, arrayIndex);
|
|
34 }
|
|
35
|
|
36 public bool Remove(T item) {
|
|
37 lock (m_components)
|
|
38 return m_components.Remove(item);
|
|
39 }
|
|
40
|
|
41 public int Count {
|
|
42 get {
|
|
43 lock (m_components)
|
|
44 return m_components.Count;
|
|
45 }
|
|
46 }
|
|
47
|
|
48 public bool IsReadOnly {
|
|
49 get {
|
|
50 return false;
|
|
51 }
|
|
52 }
|
|
53
|
|
54 public IEnumerator<T> GetEnumerator() {
|
|
55 T[] items;
|
|
56 lock (m_components) {
|
|
57 items = new T[m_components.Count];
|
|
58 m_components.CopyTo(items);
|
|
59 return (IEnumerator<T>)items.GetEnumerator();
|
|
60 }
|
|
61 }
|
|
62
|
|
63 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
|
|
64 return GetEnumerator();
|
|
65 }
|
|
66
|
|
67 public void Add(T item) {
|
|
68 Safe.ArgumentNotNull(item, "item");
|
|
69
|
|
70 lock (m_components) {
|
|
71 if (IsDisposed)
|
|
72 Safe.Dispose(item);
|
|
73 else
|
|
74 m_components.Add(item);
|
|
75 }
|
|
76 }
|
|
77
|
|
78 protected override void Dispose(bool disposing) {
|
|
79 base.Dispose(disposing);
|
|
80 Clear();
|
|
81 }
|
|
82 }
|
|
83 }
|
|
84
|