|
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.