diff --git a/Implab/Components/ComponentContainer.cs b/Implab/Components/ComponentContainer.cs --- a/Implab/Components/ComponentContainer.cs +++ b/Implab/Components/ComponentContainer.cs @@ -8,7 +8,8 @@ namespace Implab.Components { /// /// Instanses of this class are thread safe. public class ComponentContainer : Disposable, ICollection { - readonly HashSet m_components = new HashSet(); + List m_components = new List(); + readonly object m_lock = new object(); /// /// Removes currently stored compoenents from the container and disposes them if possible. @@ -17,12 +18,11 @@ namespace Implab.Components { /// A new components may be added before this method completes. /// public void Clear() { - T[] removed; + List removed; - lock (m_components) { - removed = new T[m_components.Count]; - m_components.CopyTo(removed); - m_components.Clear(); + lock (m_lock) { + removed = m_components; + m_components = new List(); } foreach (var item in removed.OfType()) @@ -34,7 +34,7 @@ namespace Implab.Components { /// /// The item to check. public bool Contains(T item) { - lock (m_components) + lock (m_lock) return m_components.Contains(item); } @@ -44,7 +44,7 @@ namespace Implab.Components { /// A destination array for components. /// A starting index in the destination array. public void CopyTo(T[] array, int arrayIndex) { - lock (m_components) + lock (m_lock) m_components.CopyTo(array, arrayIndex); } @@ -53,7 +53,7 @@ namespace Implab.Components { /// /// The item to remove. public bool Remove(T item) { - lock (m_components) + lock (m_lock) return m_components.Remove(item); } @@ -62,7 +62,7 @@ namespace Implab.Components { /// public int Count { get { - lock (m_components) + lock (m_lock) return m_components.Count; } } @@ -84,12 +84,11 @@ namespace Implab.Components { /// /// The enumerator. public IEnumerator GetEnumerator() { - T[] items; - lock (m_components) { - items = new T[m_components.Count]; + T[] items = new T[m_components.Count]; + lock (m_lock) { m_components.CopyTo(items); - return (IEnumerator)items.GetEnumerator(); } + return (IEnumerator)items.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { @@ -105,13 +104,15 @@ namespace Implab.Components { /// public void Add(T item) { Safe.ArgumentNotNull(item, "item"); - - lock (m_components) { + bool dispose = false; + lock (m_lock) { if (IsDisposed) - Safe.Dispose(item); + dispose = true; else m_components.Add(item); } + if (dispose) + Safe.Dispose(item); } /// @@ -119,8 +120,10 @@ namespace Implab.Components { /// /// If set to true the collection is disposing. protected override void Dispose(bool disposing) { + if (disposing) + Clear(); + base.Dispose(disposing); - Clear(); } } }