Click here to Skip to main content
15,885,767 members
Articles / Desktop Programming / WPF

Templates, Inversion of Control, Factories, and so on

Rate me:
Please Sign up or sign in to vote.
4.75/5 (5 votes)
8 Jul 2011CPOL11 min read 22.9K   270   18  
This article gives a little presentation of Control Templates, Data Templates, Inversion of Control, and Factories, explaining why they are all related and how to better use them.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Pfz.Caching;
using Pfz.Extensions.MonitorLockExtensions;

namespace Pfz.Threading
{
	/// <summary>
	/// This is a thread pool that, different from System.Threading.ThreadPool,
	/// does not have a thread limit and the threads are not background while
	/// they run. Comparing to the system ThreadPool, it is better if the
	/// thread can enter in wait mode. This happens when one thread has a 
	/// "fast" process, but can only terminate after another thread returns.
	/// 
	/// This thread pool keeps threads that were used alive at the next collection.
	/// So, for a thread to die, it must not be used between 2 collections.
	/// </summary>
	public static class UnlimitedThreadPool
	{
		#region Private fields
			private static object _lock = new object();
			private static List<Parameters> _freeEvents = new List<Parameters>();
		#endregion
		
		#region Constructor
			[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
			static UnlimitedThreadPool()
			{
				GCUtils.Collected += _Collected;
			}
		#endregion
		#region _Collected
			private static void _Collected()
			{
				try
				{
					int minimumCollectionNumber = GC.CollectionCount(GC.MaxGeneration);
					List<Parameters> freeEvents;
					
					lock(_lock)
					{
						freeEvents = _freeEvents;
							
						var newFreeEvents = new List<Parameters>();
						foreach(Parameters p in freeEvents)
						{
							if (p.UsedInThisGeneration)
							{
								p.UsedInThisGeneration = false;
								newFreeEvents.Add(p);
							}
							else
							{
								p.Action = null;
								p.WaitEvent.Set();
							}
						}
						_freeEvents = newFreeEvents;
					}
				}
				catch
				{
				}
			}
		#endregion
		
		#region Methods
			#region Run
				/// <summary>
				/// Runs an action in another thread. Uses an existing thread if one is 
				/// available or creates a new one if none are available, so this call will
				/// not hang if there are no available threads.
				/// </summary>
				/// <param name="action">The function to execute.</param>
				public static void Run(Action action)
				{
					Run
					(
						delegate(object obj)
						{
							action();
						},
						null
					);
				}
				
				/// <summary>
				/// Runs an action in another thread. Uses an existing thread if one is 
				/// available or creates a new one if none are available, so this call will
				/// not hang if there are no available threads.
				/// </summary>
				/// <param name="action">The function to execute.</param>
				/// <param name="parameter">The object passed as parameter to the action.</param>
				public static void Run(Action<object> action, object parameter)
				{
					if (action == null)
						throw new ArgumentNullException("action");
				
					Parameters p = null;
					lock(_lock)
					{
						int count = _freeEvents.Count;
						if (count > 0)
						{
							int index = count - 1;
							p = _freeEvents[index];
							_freeEvents.RemoveAt(index);
						}
					}
							
					if (p == null)
					{
						p = new Parameters();
						p.WaitEvent = new PooledManualResetEvent(false);
						Thread thread = new Thread(_RunThread);
						p.Thread = thread;
						thread.Start(p);
					}

					p.Action = action;
					p.Parameter = parameter;
					
					p.Thread.IsBackground = false;
					p.WaitEvent.Set();
				}
				
				/// <summary>
				/// Runs an action in another thread. Uses an existing thread if one is 
				/// available or creates a new one if none are available, so this call will
				/// not hang if there are no available threads.
				/// </summary>
				/// <typeparam name="T">The type of the parameter.</typeparam>
				/// <param name="action">The function to execute.</param>
				/// <param name="parameter">The object passed as parameter to the action.</param>
				public static void Run<T>(Action<T> action, T parameter)
				{
					Run
					(
						delegate(object obj)
						{
							T typedParameter = (T)obj;
							action(typedParameter);
						},
						parameter
					);
				}
			#endregion
			
			#region _RunThread
				private static void _RunThread(object parameters)
				{
					Thread currentThread = Thread.CurrentThread;
					Parameters p = (Parameters)parameters;
					PooledManualResetEvent waitEvent = p.WaitEvent;
					
					try
					{
						while(true)
						{
							waitEvent.WaitOne();
							
							if (p.Action == null)
								return;
							
							p.Action(p.Parameter);

							p.UsedInThisGeneration = true;
							waitEvent.Reset();
							currentThread.IsBackground = true;

							if (currentThread.Name != null)
								return;

							lock(_lock)
								_freeEvents.Add(p);
						}
					}
					finally
					{
						if (currentThread.IsBackground)
							lock(_lock)
								_freeEvents.Remove(p);


						waitEvent.Dispose();
					}
				}
			#endregion
		#endregion

		#region Parameters - Nested class
			private sealed class Parameters
			{
				internal Thread Thread;
				internal PooledManualResetEvent WaitEvent;
				internal Action<object> Action;
				internal object Parameter;
				internal bool UsedInThisGeneration;
			}
		#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)


Written By
Software Developer (Senior) Microsoft
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 (in October 2014 I started working at Microsoft, so I can't be a Microsoft MVP anymore).

Comments and Discussions