Click here to Skip to main content
15,886,091 members
Articles / Containers / Virtual Machine

Observable property pattern, memory leaks, and weak delegates for .NET

Rate me:
Please Sign up or sign in to vote.
4.96/5 (42 votes)
4 Dec 200624 min read 217.6K   359   174  
This article is dedicated to the observable property design pattern, a very nice pattern used in the Microsoft .NET Framework, a possible memory leak problem with it, and gives a couple of ways to solve it.
#region License
/*
Copyright (c) 2006 Alexey A. Popov

	Permission is hereby granted, free of charge, to any person
	obtaining a copy of this software and associated documentation
	files (the "Software"), to deal in the Software without
	restriction, including without limitation the rights to use,
	copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following
	conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
	OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;

using Pvax.WeakDelegates;

namespace Pvax.App.ConsoleTest
{
	public class Observable
	{
		const int HogSize = 10000;

		byte[] hog;

		static int subscribed = 0;

		string name;

		public Observable()
		{
			this.name = String.Empty;
			this.hog = new byte[HogSize];
		}

		public string Name
		{
			get
			{
				return name;
			}

			set
			{
				if(name != value)
				{
					CancelEventArgs e = new CancelEventArgs();
					OnNameChanging(e);
					if(e.Cancel)
						return;
					name = value;
					OnNameChanged(EventArgs.Empty);
				}
			}
		}

		EventHandler nameChanged = null;

		public event EventHandler NameChanged
		{
			add
			{
				nameChanged += value;
				Interlocked.Increment(ref subscribed);
			}

			remove
			{
				nameChanged -= value;
				Interlocked.Decrement(ref subscribed);
			}
		}

		protected virtual void OnNameChanged(EventArgs e)
		{
			EventHandler handler = nameChanged;
			if(null != handler)
				handler(this, e);
		}

		CancelEventHandler nameChanging;

		public event CancelEventHandler NameChanging
		{
			add
			{
				nameChanging += value;
			}

			remove
			{
				nameChanging -= value;
			}
		}

		protected virtual void OnNameChanging(CancelEventArgs e)
		{
			CancelEventHandler handler = nameChanging;
			if(null != handler)
				handler(this, e);
		}

		public void Unsubscribe()
		{
			nameChanging = null;
			nameChanged = null;
			subscribed = 0;
		}

		public static int Subscribed
		{
			get
			{
				return subscribed;
			}
		}

	}

	public class Observer
	{
		const int HogSize = 10000;

		byte[] hog;

		string name;

		public Observer(string name)
		{
			this.name = name;
			this.hog = new byte[HogSize];
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public void OnChanged(object sender, EventArgs e)
		{
			Trace.WriteLine("Changed event.");
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public void OnChanging(object sender, CancelEventArgs e)
		{
			Trace.WriteLine("Changing event.");
		}

	}

	delegate void ObservableCallback(Observable observable);

	delegate void WireCallback(Observable observable, Observer observer);

	class MainClass
	{
		const int MemoryNoiseObjectCount = 1000;

		const int ObserversCount = 5000;

		const int PropertyChangeCount = 5;

		const string AllocateMessageFormat = "It took {0} seconds to allocate and wire up {1} observers with {2} delegates for pre- and postnotifications.";
		const string WireMessageFormat = "It took {0} seconds to change the Name property {1} times and pre-notify/notify the obvservers.";
		const string StartMessageFormat = "Start number of subscriptions: {0}";
		const string FinishMessageFormat = "Final number of subscriptions: {0}";
		const string GCMessageFormat = "Number of subscriptions after forced garbage collection: {0}";

		static void GenerateMemoryNoise()
		{
			object[] objects = new object[MemoryNoiseObjectCount];
			Random rnd = new Random(DateTime.Now.Millisecond);
			for(int i = 0; i < MemoryNoiseObjectCount; i++)
			{
				int oType = rnd.Next(4);
				switch(oType)
				{
					case 0:
						objects[i] = new object();
						break;
					case 1:
						objects[i] = Guid.NewGuid().ToString();
						break;
					case 2:
						objects[i] = DateTime.Now;
						break;
					case 3:
						objects[i] = rnd.Next(256);
						break;
					case 4:
						objects[i] = rnd.NextDouble();
						break;
				}
			}
		}

		static void Set(Observable observable)
		{
			observable.Name = Guid.NewGuid().ToString();
		}

		static TimeSpan MeasureSet(Observable observable, int times)
		{
			DateTime start = DateTime.Now;
			for(int i = 0; i < times; i++)
			{
				Set(observable);
			}
			return DateTime.Now - start;
		}

		static void TestRunner(Observable observable, int observables, int times, WireCallback test, ObservableCallback postTest, string delegateType)
		{
			GenerateMemoryNoise();
			Console.WriteLine(StartMessageFormat, Observable.Subscribed);
			DateTime start, finish;
			// This array prevents the observers from being prematurely garbage collected
			Observer[] observer = new Observer[observables];
			start = DateTime.Now;
			for(int i = 0; i < observables; i++)
			{
				observer[i] = new Observer("Observer" + i);
				test(observable, observer[i]);
			}
			finish = DateTime.Now;
			Console.WriteLine(AllocateMessageFormat, finish - start, observables, delegateType);
			Console.WriteLine(WireMessageFormat, MeasureSet(observable, times), times);
			Console.WriteLine(FinishMessageFormat, Observable.Subscribed);
			for(int i = 0; i < observables; i++)
				observer[i] = null;
			observer = null;
			if(null != postTest)
				postTest(observable);

			ForceGC();
			Console.WriteLine(GCMessageFormat, Observable.Subscribed);
			Console.WriteLine("------------------------------------------------------");
			Console.ReadLine();
		}

		static void TestStrongEvent(Observable observable, Observer observer)
		{
			observable.NameChanged += new EventHandler(observer.OnChanged);
		}

		static void TestStrongEvent2(Observable observable, Observer observer)
		{
			observable.NameChanged += new EventHandler(observer.OnChanged);
			observable.NameChanging += new CancelEventHandler(observer.OnChanging);
		}

		static void TestWeakEvent(Observable observable, Observer observer)
		{
			// Use reflection
			observable.NameChanged += (EventHandler)WeakDelegateDecorator.Decorate(observable, "NameChanged", observer, "OnChanged");
		}

		static void TestWeakEvent2(Observable observable, Observer observer)
		{
			// Use provided delegates
			observable.NameChanged += (EventHandler)WeakDelegateDecorator.Decorate(observable, "NameChanged", new EventHandler(observer.OnChanged));
			observable.NameChanging += (CancelEventHandler)WeakDelegateDecorator.Decorate(observable, "NameChanging", new CancelEventHandler(observer.OnChanging));
		}

		static void ForceGC()
		{
			GC.Collect();
			GC.WaitForPendingFinalizers();
			GC.Collect();
		}

		static void UnsubscribeAll(Observable observable)
		{
			observable.Unsubscribe();
		}

		public static void Main(string[] args)
		{
			Observable observable = new Observable();
			TestRunner(observable, ObserversCount, PropertyChangeCount, new WireCallback(TestStrongEvent), new ObservableCallback(UnsubscribeAll), "strong");
			TestRunner(observable, ObserversCount, PropertyChangeCount, new WireCallback(TestStrongEvent2), new ObservableCallback(UnsubscribeAll), "strong");
			TestRunner(observable, ObserversCount, PropertyChangeCount, new WireCallback(TestWeakEvent), null, "weak");
			TestRunner(observable, ObserversCount, PropertyChangeCount, new WireCallback(TestWeakEvent2), null, "weak");
		}
	}
}

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Russian Federation Russian Federation
I'm a system administrator from Moscow, Russia. Programming is one of my hobbies. I presume I'm one of the first Russians who created a Web site dedicated to .Net known that time as NGWS. However, the Web page has been abandoned a long ago.

Comments and Discussions