Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Threading & .NET


Michael is a senior software developer working with .NET. Michael can be reached at [email protected].


Even though threading has been around a long time, many developers still struggle with writing multithreaded code. A quick scan of the Microsoft forums, for instance, reveals that developers are constantly struggling with multithreading issues, even with the advances in .NET. There are already many articles written about writing thread-safe code, including how to use the Thread and ThreadPool classes, how to pass data between threads, and how and why to synchronize access to shared data.

In this article, I focus on areas that are lacking—pausing/resuming threads, communicating with UI components, and canceling threads. These operations are usually required by apps, but aren't always easy to write. Granted, there are already methods in the Thread class to support these operations, but they should be avoided.

The code I present here includes a framework that you can use to provide additional threading capabilities as they are described in this article. The complete source code for the framework, which was written for the .NET Framework 2.0 but can be modified to work with 1.x, is available at http://www.ddj.com/code/. I also include a test application to test the threading capabilities. Finally, the framework can be extended to include new functionality if needed.

Work Items

A "work item" is the logic that runs in a separate thread. A work item may or may not support canceling and pausing. Pausing and canceling work items require careful handshaking between the thread running the work item and any shared resources used by the work item. Therefore, by default, a work item supports neither. In the framework I present here, the WorkItem class (Listing One) represents a work item. To support canceling or pausing, a class deriving from WorkItem must be created.

 
namespace DDJ.Threading
{	
	// Represents work that is done in a secondary thread.
	public class WorkItem
	{
		//Constructors
		protected WorkItem ( )
		{ /* Do nothing */ }

		public WorkItem ( ThreadStart workDelegate )
		{
			m_WorkDelegate = workDelegate;
		}

		//Public Members

		// The default is false.
		public virtual bool CanCancel
		{
			get { return false; }
		}

		// The default is false.
		public virtual bool CanPause
		{
			get { return false; }
		}

		//Protected Members
		protected internal WorkItemThread InnerThread
		{
			get { return m_Thread; }
		}

		// If the thread is paused then this method will block.
		protected bool CheckState ( )
		{
			return (InnerThread != null) ? InnerThread.CheckState() 
					: false;
		}

		// The base class calls the method specified by the work
		// delegate passed to the constructor.		
		protected virtual void DoWorkBase ( )
		{
			if (m_WorkDelegate != null)
				m_WorkDelegate();			
		}

		//Internal Members
		internal void DoWork ( )
		{			
			DoWorkBase();
		}

		internal void SetThread ( WorkItemThread thread )
		{
			m_Thread = thread;
		}
		
		//Private Data
		private ThreadStart m_WorkDelegate;
		private WorkItemThread m_Thread;
	}
}
Listing One

Work items do not manage the state of the thread upon which they are currently running. Other than checking the state of the thread periodically, a work item is only interested in completing its work. The WorkItemThread (Listing Two) manages the state of the work item's thread and is responsible for handling state change requests. WorkItemThread uses the associated work item to determine whether a request is supported. In return, WorkItem uses the associated work item thread to determine if it is okay to execute.

 
namespace DDJ.Threading
{
	//Represents a logical thread executing a WorkItem object.
	public sealed class WorkItemThread
	{
		// Constructors
				
		static WorkItemThread ( )
		{
			//Initializes the state machine used to control state
		}

		internal WorkItemThread ( WorkItem item )
		{
			m_Item = item;
		}

		// Public Members

		// Occurs after the state of the thread changes.
		public event EventHandler StateChanged;

		public bool CanCancel
		{
			get { return m_Item.CanCancel; }
		}

		public bool CanPause
		{
			get { return m_Item.CanPause; }
		}

		public WorkItem Item
		{
			get { return m_Item; }
		}

		public WorkItemThreadState State
		{
			get { return m_State; }
		}

		// The method does not wait for the work item to be cancelled.
		public void Cancel ( )
		{
			//Check
			if (!CanCancel)
				throw new NotSupportedException("Cancel is not supported.");

			//Move to the appropriate state
			SetState(WorkItemThreadState.Cancelling);
		}

		// If the work item is already paused then nothing happens.
		// The method does not wait for the work item to pause.
		public void Pause ( )
		{
			//Check
			if (!CanPause)
				throw new NotSupportedException("Pause is not supported.");

			SetState(WorkItemThreadState.Pausing);
		}

		// If the work item is not paused then nothing happens.
		// The method does not wait for the work item to resume.
		public void Resume ( )
		{
			SetState(WorkItemThreadState.Resuming);
		}

		// Terminating a work item may cause a resource leak or deadlock
		// depending on what the work item was doing when the thread was
		// terminated.  Use this method only in extreme circumstances.
		// The method does not wait for the work item to be terminated.
		public void Terminate ( )
		{
			SetState(WorkItemThreadState.Terminating);
		}

		// Internal Members

		// This is a blocking call if the thread is paused.
		internal bool CheckState ( )
		{
			//State machine so we may transition between states			
			while (true)
			{
				switch (m_State)
				{
					case WorkItemThreadState.Cancelling: 
						SetState(WorkItemThreadState.Cancelled); break;

					case WorkItemThreadState.Resuming: 
						SetState(WorkItemThreadState.Running); break;

					case WorkItemThreadState.Running: return true;

					case WorkItemThreadState.Paused:
					{
						//Block until we aren't paused anymore
						m_evtStateChanged.WaitOne();
						break;
					};
					case WorkItemThreadState.Pausing: 
						SetState(WorkItemThreadState.Paused); break;

					case WorkItemThreadState.Cancelled:
					case WorkItemThreadState.Finished:
					case WorkItemThreadState.Terminated: return false;
						
					case WorkItemThreadState.Terminating: 
						SetState(WorkItemThreadState.Terminated); break;					
				};
			};
		}

		// Thread routine
		internal void DoWork ( )
		{
			//Check the state of the thread first
			if (!CheckState())
				return;

			try
			{
				m_Item.DoWork();
			} catch (ThreadAbortException)
			{
				SetState(WorkItemThreadState.Terminated);
			};

			//Done
			if (CheckState())
				SetState(WorkItemThreadState.Finished);

			//Clear the work item's thread so it can be reused
			m_Item.SetThread(null);
		}

		// Private Members

		#region Methods

		//State must be locked already
		private bool MoveToState ( WorkItemThreadState newState )
		{
			//Is the transition valid?
			switch (m_StateMachine[(int)m_State, (int)newState])
			{
				case StateChangeAction.Error: 
					throw new InvalidOperationException(
						String.Concat("Unable to move from ", 
							m_State.ToString(), " to ", 
							newState.ToString()));					
				case StateChangeAction.Ignore: return false;
				case StateChangeAction.Success: 
					m_State = newState; return true;				
			};

			return false;
		}

		private void OnStateChanged ( )
		{
			EventHandler hdlr = StateChanged;
			if (hdlr != null)
				hdlr(this, EventArgs.Empty);
		}

		private void SetState ( WorkItemThreadState newState )
		{
			//Quick check, if the states are equal then forget it
			if (m_State == newState)
				return;

			//Lock the state flag temporarily
			bool bChanged = false;
			lock(m_lckState)
			{
				//Check again as the state may have changed
				if (m_State == newState)
					return;

				//Move to the new state
				bChanged = MoveToState(newState);
			};

			//If the state changed then notify anybody who cares
			if (bChanged)
			{
				OnStateChanged();
				m_evtStateChanged.Set();
			};
		}
		#region Data

		private WorkItem m_Item;

		//State management
		private WorkItemThreadState m_State;
		private AutoResetEvent m_evtStateChanged = new AutoResetEvent(false);

		//Simple state machine
		private static StateChangeAction[,] m_StateMachine;
		#endregion
	}
}
Listing Two


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.