Click here to Skip to main content
11,707,470 members (70,453 online)
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 11K 306 25
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.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Pfz.Caching;

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.RegisterForCollectedNotification(_collector);
			}
		#endregion
		#region _Collected
			private static readonly UnlimitedThreadPoolCollector _collector = new UnlimitedThreadPoolCollector();
			private sealed class UnlimitedThreadPoolCollector:
				IGarbageCollectionAware
			{
				public void OnCollected()
				{
					try
					{
						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 ManagedManualResetEvent();
						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;
					var waitEvent = p.WaitEvent;
					
					try
					{
						currentThread.IsBackground = true;

						while(true)
						{
							waitEvent.WaitOne();
							
							if (p.Action == null)
								return;
							
							currentThread.IsBackground = false;
							p.Action(p.Parameter);

							if (currentThread.Name != null)
								return;

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

							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 ManagedManualResetEvent 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)

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, 2015
Microsoft MVP 2013-2014

You may also be interested in...

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