Click here to Skip to main content
13,191,400 members (75,382 online)
Click here to Skip to main content
Articles » Languages » C# » General » Downloads

Tagged as

Stats

15.4K views
353 downloads
27 bookmarked
Posted 1 Dec 2011

Lazy Alternatives - LazyAndWeak and BackgroundLoader

, 1 Dec 2011
This article will present two alternatives to Lazy.
LazyAlternatives
LazyAlternatives.suo
LazyAlternativesSample
Properties
Pfz
Caching
Collections
DataTypes
DynamicObjects
Internal
Extensions
Factoring
Pfz.csproj.user
Pfz.Phone.csproj.user
Pfz.ruleset
Pfz.Silverlight.csproj.user
Pfz.snk
Pfz.suo
PhoneSpecific
Properties
Remoting
Instructions
Internal
Serializers
Udp
Serialization
BinaryBuiltIn
Threading
Contexts
Disposers
Unsafe
using System;
using System.Collections.Generic;
using System.Linq;
using Pfz.Threading;

namespace Pfz.Caching
{
	/// <summary>
	/// This class acts as a hashset for delegates, but allows the
	/// Targets to be collected, working as if the Delegates where 
	/// WeakDelegates.
	/// The original idea was to make this a generic class, but it
	/// is not possible to use Delegate as a constraint (where T: Delegate).
	/// 
	/// To use, implement your event like:
	/// private WeakDelegateSet _myEvent = new WeakDelegateSet();
	/// public event EventHandler MyEvent
	/// {
	///		add
	///		{
	///			_myEvent.Add(value);
	///		}
	///		remove
	///		{
	///			_myEvent.Remove(value);
	///		}
	///		
	/// And when you want to invoke MyEvent, you call:
	///		_myEvent.Invoke(this, EventArgs.Empty);
	/// }
	/// </summary>
	public class WeakDelegateSet:
		ReaderWriterSafeDisposable
	{
		#region Private dictionary
			private Dictionary<int, List<InternalWeakDelegate>> _dictionary = new Dictionary<int, List<InternalWeakDelegate>>();
		#endregion
	
		#region Constructor
			/// <summary>
			/// Creates a new WeakDelegateSet.
			/// </summary>
			public WeakDelegateSet()
			{
				GCUtils.Collected += _Collected;
			}
		#endregion
		#region Dispose
			/// <summary>
			/// Unregisters the WeakDelegateSet from GCUtils.Collected.
			/// </summary>
			/// <param name="disposing"></param>
			protected override void Dispose(bool disposing)
			{
				if (disposing)
					GCUtils.Collected -= _Collected;
					
				base.Dispose(disposing);
			}
		#endregion
		#region _Collected
			private void _Collected()
			{
				try
				{
					using(var upgradeableLock = DisposeLock.UpgradeableLock())
					{
						if (WasDisposed)
						{
							GCUtils.Collected -= _Collected;
							return;
						}
							
						var oldDictionary = _dictionary;
						var newDictionary = new Dictionary<int, List<InternalWeakDelegate>>();
							
						foreach(var pair in oldDictionary)
						{
							List<InternalWeakDelegate> oldList = pair.Value;
							List<InternalWeakDelegate> newList = new List<InternalWeakDelegate>(oldList.Count);
							foreach(InternalWeakDelegate handler in oldList)
								if (handler.Method.IsStatic || handler.Target != null)
									newList.Add(handler);
								
							if (newList.Count > 0)
								newDictionary.Add(pair.Key, newList);
						}
							
						upgradeableLock.Upgrade();
						_dictionary = newDictionary;
					}
				}
				catch
				{
				}
			}
		#endregion
		
		#region Clear
			/// <summary>
			/// Clears the delegate set.
			/// </summary>
			public void Clear()
			{
				using(DisposeLock.WriteLock())
				{
					CheckUndisposed();
						
					_dictionary.Clear();
				}
			}
		#endregion
		#region Add
			/// <summary>
			/// Adds a new handler to the delegate set.
			/// </summary>
			/// <param name="handler">The handler to add.</param>
			/// <returns>true if the delegate was new to the set, false otherwise.</returns>
			public bool Add(Delegate handler)
			{
				if (handler == null)
					throw new ArgumentNullException("handler");
			
				int hashCode = handler.GetHashCode();
			
				using(var upgradeableLock = DisposeLock.UpgradeableLock())
				{
					CheckUndisposed();
						
					var dictionary = _dictionary;
						
					List<InternalWeakDelegate> list;
					if (dictionary.TryGetValue(hashCode, out list))
					{
						foreach(InternalWeakDelegate action in list)
							if (action.Target == handler.Target && action.Method == handler.Method)
								return false;

						upgradeableLock.Upgrade();
					}
					else
					{
						list = new List<InternalWeakDelegate>(1);

						upgradeableLock.Upgrade();
						dictionary.Add(hashCode, list);
					}
						
					InternalWeakDelegate weakDelegate = new InternalWeakDelegate(handler);
					list.Add(weakDelegate);
				}

				return true;
			}
		#endregion
		#region Remove
			/// <summary>
			/// Removes a handler from the delegate set.
			/// </summary>
			/// <param name="handler">The handler to remove.</param>
			/// <returns>true if the item was in the set, false otherwise.</returns>
			public bool Remove(Delegate handler)
			{
				if (handler == null)
					throw new ArgumentNullException("handler");
			
				int hashCode = handler.GetHashCode();

				using(var upgradeableLock = DisposeLock.UpgradeableLock())
				{
					CheckUndisposed();

					var dictionary = _dictionary;
						
					List<InternalWeakDelegate> list;
					if (!dictionary.TryGetValue(hashCode, out list))
						return false;
						
					int count = list.Count;
					for(int i=0; i<count; i++)
					{
						InternalWeakDelegate weakDelegate = list[i];
						if (weakDelegate.Method == handler.Method && weakDelegate.Target == handler.Target)
						{
							upgradeableLock.Upgrade();
							list.RemoveAt(i);
							return true;
						}
					}
				}
				
				return false;
			}
		#endregion
		
		#region Invoke
			/// <summary>
			/// Invokes all the handlers in the set with the given parameters.
			/// </summary>
			/// <param name="parameters">The parameters to be used in the invoke of each handler.</param>
			public void Invoke(params object[] parameters)
			{
				List<List<InternalWeakDelegate>> copy;
				
				using(DisposeLock.ReadLock())
				{
					CheckUndisposed();
						
					copy = new List<List<InternalWeakDelegate>>(_dictionary.Values.ToList());
				}
				
				foreach(var list in copy)
				{
					foreach(var handler in list)
					{
						object target = handler.Target;
						if (target != null || handler.Method.IsStatic)
							handler.Method.Invoke(target, parameters);
					}
				}
			}
		#endregion
	}
}

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)

Share

About the Author

Paulo Zemek
Engineer YouTube
United States United States
I started to program computers when I was 11 years old, as a hobbyist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.

At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do their work easier, faster and with less errors.

Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: paulozemek@outlook.com

Codeproject MVP 2012, 2015 & 2016
Microsoft MVP 2013-2014 (now I work at Microsoft so I can't be a Microsoft MVP anymore)

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171017.1 | Last Updated 1 Dec 2011
Article Copyright 2011 by Paulo Zemek
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid