Click here to Skip to main content
15,891,316 members
Articles / Programming Languages / C#

Asynchronous Multi-threaded ObservableCollection

Rate me:
Please Sign up or sign in to vote.
4.85/5 (18 votes)
9 May 2014CPOL6 min read 124.7K   4.4K   112  
An implementation of of a multi-threaded ObservableCollection.
using System;
using System.Collections;
using System.Collections.Generic;

namespace CollectionMtLib
{
	public class BlockingIterator<T> : IDisposable, IEnumerator<T>
	{
		private IEnumerator<T> _iEnumerator = null;
		private object _objLock = null;

		public T Current
		{
			get { return _iEnumerator.Current; }
		}

		object IEnumerator.Current
		{
			get { return _iEnumerator.Current; }
		}

		public bool MoveNext()
		{
			return _iEnumerator.MoveNext();
		}

		public void Reset()
		{
			_iEnumerator.Reset();
		}

		private bool _disposed = false;

		// The stream passed to the constructor  
		// must be readable and not null. 
		public BlockingIterator(IEnumerator<T> iEnumerator, object objLock)
		{
			if (iEnumerator == null || objLock == null)
			{
				throw new ArgumentException();
			}

			_iEnumerator = iEnumerator;
			_objLock = objLock;
			System.Threading.Monitor.Enter(_objLock);
		}

		public void Dispose()
		{
			Dispose(true);

			// Use SupressFinalize in case a subclass 
			// of this type implements a finalizer.
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			// If you need thread safety, use a lock around these  
			// operations, as well as in your methods that use the resource. 
			if (!_disposed)
			{
				if (disposing)
				{
					if (_objLock != null)
					{
						System.Threading.Monitor.Exit(_objLock);
						_objLock = null;
					}

					var dispoable = _iEnumerator as IDisposable;
					if (dispoable != null)
					{
						dispoable.Dispose();
						_iEnumerator = null;
					}
				}

				// Indicate that the instance has been disposed.
				_disposed = true;
			}
		}

	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer IREQ - Hydro-Quebec
Canada Canada
Hi,

I'm a french Canadian software developer.
Work at Hydro-Quebec / IREQ.
Live in Sainte-Julie, Quebec, Canada (South shore of Montreal)

WebPage: http://www.ericouellet.com
GMail: ericouellet2

Salut!

Comments and Discussions