Click here to Skip to main content
Click here to Skip to main content
Articles » Languages » C# » General » Downloads
 
Add your own
alternative version

Tagged as

Lazy Alternatives - LazyAndWeak and BackgroundLoader

, 1 Dec 2011 CPOL
This article will present two alternatives to Lazy.
LazyAlternatives.zip
LazyAlternatives
LazyAlternatives.suo
LazyAlternativesSample
Properties
Settings.settings
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;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Pfz.Threading;
using System.Runtime.InteropServices;

namespace Pfz.Caching
{
	/// <summary>
	/// This is a dictionary that allow values to be collected.
	/// </summary>
	[Serializable]
	public sealed class WeakDictionary<TKey, TValue>:
		ReaderWriterSafeDisposable,
		IDictionary<TKey, TValue>,
		IGarbageCollectionAware
	where
		TValue: class
	{
		#region Static Area
			private static ConstructorInfo _valueConstructor = typeof(TValue).GetConstructor(Type.EmptyTypes);
		#endregion

		#region Private dictionary of KeepAliveGCHandle
			private Dictionary<TKey, WeakReference> _dictionary = new Dictionary<TKey, WeakReference>();
		#endregion
		
		#region Constructor
			/// <summary>
			/// Creates the dictionary.
			/// </summary>
			public WeakDictionary()
			{
				GCUtils.RegisterForCollectedNotification(this);
			}
		#endregion
		#region Dispose
			/// <summary>
			/// Frees all handles used to know if an item was collected or not.
			/// </summary>
			protected override void Dispose(bool disposing)
			{
				if (disposing)
					GCUtils.UnregisterFromCollectedNotification(this);
				
				_dictionary = null;
				
				base.Dispose(disposing);
			}
		#endregion
		#region _Collected
			void IGarbageCollectionAware.OnCollected()
			{
				try
				{
					using(DisposeLock.WriteLock())
					{
						if (WasDisposed)
						{
							GCUtils.UnregisterFromCollectedNotification(this);
							return;
						}
							
						var oldDictionary = _dictionary;
						var newDictionary = new Dictionary<TKey, WeakReference>(oldDictionary.Count);
						foreach(var pair in oldDictionary)
						{
							var handle = pair.Value;
							
							if (handle.Target != null)
								newDictionary.Add(pair.Key, pair.Value);
						}
						
						_dictionary = newDictionary;
					}
				}
				catch
				{
				}
			}
		#endregion
		
		#region Properties
			#region Count
				/// <summary>
				/// Gets the number of items in this dictionary.
				/// </summary>
				public int Count
				{
					get
					{
						using(DisposeLock.ReadLock())
						{
							CheckUndisposed();
							
							return _dictionary.Count;
						}
					}
				}
			#endregion
			#region this[]
				/// <summary>
				/// Gets or sets a value for the specified key.
				/// Returns null if the item does not exist. The indexer, when
				/// used as an IDictionary throws an exception when the item does
				/// not exist.
				/// </summary>
				public TValue this[TKey key]
				{
					get
					{
						if (key == null)
							throw new ArgumentNullException("key");
					
						using(DisposeLock.ReadLock())
						{
							CheckUndisposed();
							
							WeakReference handle;
							if (_dictionary.TryGetValue(key, out handle))
								return (TValue)handle.Target;
						}

						return default(TValue);
					}
					set
					{
						if (key == null)
							throw new ArgumentNullException("key");
					
						using(DisposeLock.WriteLock())
						{
							CheckUndisposed();
							
							if (value == null)
								_Remove(key);
							else
							{
								WeakReference handle;
								
								var dictionary = _dictionary;
								if (dictionary.TryGetValue(key, out handle))
									handle.Target = value;
								else
									_Add(key, value, dictionary);
							}
						}
					}
				}
			#endregion
			
			#region Keys
				/// <summary>
				/// Gets the Keys that exist in this dictionary.
				/// </summary>
				public ICollection<TKey> Keys
				{
					get
					{
						using(DisposeLock.ReadLock())
						{
							CheckUndisposed();
							
							return _dictionary.Keys.ToArray();
						}
					}
				}
			#endregion
			#region Values
				/// <summary>
				/// Gets a copy of the values that exist in this dictionary.
				/// </summary>
				public ICollection<TValue> Values
				{
					get
					{
						using(DisposeLock.ReadLock())
						{
							CheckUndisposed();
							
							var dictionary = _dictionary;

							List<TValue> result = new List<TValue>();
							foreach(var handle in dictionary.Values)
							{
								TValue item = (TValue)handle.Target;
								if (item != null)
									result.Add(item);
							}
							
							return result;
						}
					}
				}
			#endregion
		#endregion
		#region Methods
			#region _CreateValue
				private static TValue _CreateValue()
				{
					if (_valueConstructor == null)
						throw new NotSupportedException("Type " + typeof(TValue).FullName + " does not has a public default constructor.");

					return (TValue)_valueConstructor.Invoke(null);
				}
			#endregion

			#region Clear
				/// <summary>
				/// Clears all items in this dictionary.
				/// </summary>
				public void Clear()
				{
					using(DisposeLock.WriteLock())
					{
						CheckUndisposed();
						
						var dictionary = _dictionary;
						dictionary.Clear();
					}
				}
			#endregion
			#region GetOrCreateValue
				/// <summary>
				/// Gets the value for the given key or, if it does not exist, creates it, adds it and
				/// returns it.
				/// </summary>
				public TValue GetOrCreateValue(TKey key)
				{
					if (key == null)
						throw new ArgumentNullException("key");
					
					object result;
					using(var upgradeableLock = DisposeLock.UpgradeableLock())
					{
						CheckUndisposed();

						var dictionary = _dictionary;
						WeakReference handle;
						if (dictionary.TryGetValue(key, out handle))
						{
							result = handle.Target;
							if (result != null)
								return (TValue)result;
							
							var typedResult = _CreateValue();
							upgradeableLock.Upgrade();
							handle.Target = typedResult;
							return typedResult;
						}
						else
						{
							var typedResult = _CreateValue();
							upgradeableLock.Upgrade();
							_Add(key, typedResult, dictionary);
							return typedResult;
						}
					}
				}
			#endregion
			#region Add
				/// <summary>
				/// Adds an item to this dictionary. Throws an exception if an item
				/// with the same key already exists.
				/// </summary>
				public void Add(TKey key, TValue value)
				{
					if (key == null)
						throw new ArgumentNullException("key");
						
					if (value == null)
						throw new ArgumentNullException("value");
						
					using(DisposeLock.WriteLock())
					{
						CheckUndisposed();
						
						var dictionary = _dictionary;
						WeakReference handle;
						if (dictionary.TryGetValue(key, out handle))
						{
							if (handle.Target != null)
								throw new ArgumentException("An element with the same key \"" + key + "\" already exists.");
							
							handle.Target = value;
						}
						else
							_Add(key, value, dictionary);
					}
				}
			#endregion
			#region Remove
				/// <summary>
				/// Removes an item with the given key from the dictionary.
				/// </summary>
				public bool Remove(TKey key)
				{
					if (key == null)
						throw new ArgumentNullException("key");
					
					using(DisposeLock.WriteLock())
					{
						CheckUndisposed();

						return _Remove(key);
					}
				}
			#endregion
			
			#region ContainsKey
				/// <summary>
				/// Gets a value indicating if an item with the specified key exists.
				/// </summary>
				public bool ContainsKey(TKey key)
				{
					return _dictionary.ContainsKey(key);
				}
			#endregion
			
			#region GetEnumerator
				/// <summary>
				/// Gets an enumerator with all key/value pairs that exist in
				/// this dictionary.
				/// </summary>
				public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
				{
					return ToList().GetEnumerator();
				}
			#endregion
			#region ToList
				/// <summary>
				/// Gets a list with all non-collected key/value pairs.
				/// </summary>
				public List<KeyValuePair<TKey, TValue>> ToList()
				{
					using(DisposeLock.ReadLock())
					{
						CheckUndisposed();

						var dictionary = _dictionary;
						var result = new List<KeyValuePair<TKey, TValue>>(dictionary.Count);
						
						foreach(var pair in dictionary)
						{
							TValue target = (TValue)pair.Value.Target;
							if (target != null)
								result.Add(new KeyValuePair<TKey, TValue>(pair.Key, target));
						}

						return result;
					}
				}
			#endregion
			
			#region _Add
				[SuppressMessage("Microsoft.Usage", "CA2219:DoNotRaiseExceptionsInExceptionClauses")]
				private static void _Add(TKey key, TValue value, Dictionary<TKey, WeakReference> dictionary)
				{
					dictionary.Add(key, new WeakReference(value));
				}
			#endregion
			#region _Remove
				private bool _Remove(TKey key)
				{
					var dictionary = _dictionary;
					return dictionary.Remove(key);
				}
			#endregion
		#endregion
		#region Interfaces
			#region IDictionary<TKey,TValue> Members
				bool IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)
				{
					value = this[key];
					return value != null;
				}
				TValue IDictionary<TKey, TValue>.this[TKey key]
				{
					get
					{
						TValue result = this[key];
						if (result == null)
							throw new KeyNotFoundException("The given key \"" + key + "\" was not found in the dictionary.");
						
						return result;
					}
					set
					{
						this[key] = value;
					}
				}
			#endregion
			#region ICollection<KeyValuePair<TKey,TValue>> Members
				void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
				{
					Add(item.Key, item.Value);
				}
				bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
				{
					if (item.Value == null)
						return false;
				
					WeakReference handle;
					if (!_dictionary.TryGetValue(item.Key, out handle))
						return false;
					
					return object.Equals(handle.Target, item.Value);
				}
				void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
				{
					ToList().CopyTo(array, arrayIndex);
				}
				bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
				{
					get
					{
						return false;
					}
				}
				bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
				{
					if (item.Value == null)
						return false;
				
					using(var upgradeableLock = DisposeLock.UpgradeableLock())
					{
						CheckUndisposed();
						
						WeakReference handle;
						var dictionary = _dictionary;
						if (!dictionary.TryGetValue(item.Key, out handle))
							return false;
						
						if (!object.Equals(handle.Target, item.Value))
							return false;

						upgradeableLock.Upgrade();
						return _Remove(item.Key);
					}
				}
			#endregion
			#region IEnumerable Members
				IEnumerator IEnumerable.GetEnumerator()
				{
					return GetEnumerator();
				}
			#endregion
		#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 Microsoft Corporation
United States United States
I started to program computers when I was 11 years old, as a hobbist, 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 they work easier, faster and with less errors.
 
Now I just started working as a Senior Software Engineer at Microsoft.
 
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
Microsoft MVP 2013-2014

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