Click here to Skip to main content
15,892,005 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.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using CollectionMtLib;

namespace WpfTestObservableCollectionMt
{
	public class MainWindowModel
	{
		public CollectionMtWithAsyncObservableCollectionReadOnlyCopy<string> ObsCollMt { private set; get; }

		public MainWindowModel()
		{
			ObsCollMt = new CollectionMtWithAsyncObservableCollectionReadOnlyCopy<string>();
		}

		public void RunTest()
		{
			for (int n = 0; n < 10; n++)
			{
				Task.Factory.StartNew(ModifyCollectionRandom);
			}
		}

		static Random rnd = new Random();

		private void ModifyCollectionRandom()
		{
			while(true)
			{
				int rndNumber = rnd.Next(100);
				if (rndNumber > 95)
				{
					// Give a break to the UI to show data, otherwise it will only process collection related messages 
					// without having time to process rendering messages than are in lower priority.
					Thread.Sleep(1000);		
				}
				if (rndNumber > 30)
				{
					ObsCollMt.Add(rndNumber.ToString(CultureInfo.InvariantCulture));
				}
				else if (rndNumber > 0)
				{
					lock (ObsCollMt.SyncRoot)
					{
						if (ObsCollMt.Count > 0)
						{
							ObsCollMt.UnsafeRemoveAt(0);
						}
					}
				}
				else
				{ 
					ObsCollMt.Clear();
				}
			}
		}
	}
}

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