Click here to Skip to main content
15,880,891 members
Articles / Programming Languages / C#

Multi-threaded polling process - base for NT-Service

Rate me:
Please Sign up or sign in to vote.
3.08/5 (19 votes)
23 Mar 2003 52.6K   1.6K   24  
This is a simple skeleton for a multi-thread process or services
using System;
using System.Threading;
using System.Diagnostics;

namespace Threads
{
	/// <summary>
	/// Summary description for CWorker.
	/// </summary>
	public class WorkerThread
	{
		private int				_nID;
		private AutoResetEvent	_JobDoneEvent;

		/// <summary>
		/// WorkerThread constructor. The thread is created in stopped state.
		/// </summary>
		/// <param name="nID">ID for this thread</param>
		/// <param name="oJobDoneEvent">Event to set when job is completed</param>
		public WorkerThread(int nID, AutoResetEvent oJobDoneEvent)
		{
			_nID = nID;
			_JobDoneEvent = oJobDoneEvent;
		}
		/// <summary>
		/// Start the thread
		/// </summary>
		/// <returns>true if thread is started, false if problems occur</returns>
		public bool Start()
		{
			return ThreadPool.QueueUserWorkItem(new WaitCallback(this.ThreadCallBack));
		}
		/// <summary>
		/// WorkerThread callback
		/// </summary>
		private void ThreadCallBack(object oNotUsed)
		{
			Trace.WriteLine(String.Format("  Thread [{0}] starting.", _nID));

			//
			// Doing extremelly important thing: take a small break !
			//
			try
			{
				DoSomethingUseful();
			}
			catch(Exception E)
			{
				Trace.WriteLine(String.Format("  Thread [{0}] exception.\r\n{1}", _nID, E.ToString()));
			}

			Trace.WriteLine(String.Format("  Thread [{0}] completed.", _nID));
			//
			// Set Job Done Flag
			//
			_JobDoneEvent.Set();
		}
		/// <summary>
		/// Working thread main task
		/// </summary>
		private void DoSomethingUseful()
		{
			//
			// TODO: add here your code.
			//

			//
			// Very useful: a small nap !
			//
			Random oRnd = new Random();
			int  nSleepTime = oRnd.Next(2000);
			Thread.Sleep(nSleepTime);
		}
	}
}

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions