|
using System;
using System.Threading;
using System.Diagnostics;
namespace Threads
{
/// <summary>
/// Summary description for WorkerThreadManager.
/// </summary>
public class WorkerThreadManager
{
private Thread _InternalThread;
private ManualResetEvent _QueryStopEvent;
private ManualResetEvent _StopCompletedEvent;
private int _ThreadCount;
private int _PollTime;
private int _TimeOut;
public WorkerThreadManager()
{
_QueryStopEvent = new ManualResetEvent(false);
_StopCompletedEvent = new ManualResetEvent(false);
_ThreadCount = 5; // 5 thread to create
_PollTime = 10000; // wait 10s between iteration
_TimeOut = 5000; // wait 5s for a complete iteration
}
/// <summary>
/// WorkerThreadMonitor callback
/// </summary>
private void ThreadCallBack()
{
Trace.WriteLine("WorkerThreadManager::ThreadCallBack - BEGIN");
//
// Be sure that completed event is not set
//
_StopCompletedEvent.Reset();
do
{
//
// Create Working threads
//
AutoResetEvent[] aCompletedEvents = new AutoResetEvent[_ThreadCount];
for (int i = 0; i < _ThreadCount; i++)
{
aCompletedEvents[i] = new AutoResetEvent(false);
WorkerThread oWorker = new WorkerThread(i, aCompletedEvents[i]);
oWorker.Start();
//
// Wait a little before creating new thread to avoid
//
Thread.Sleep(1);
}
WaitHandle.WaitAll(aCompletedEvents, _TimeOut, false);
}
while (_QueryStopEvent.WaitOne(_PollTime, false) == false);
//
// Stop completed
//
_StopCompletedEvent.Set();
Trace.WriteLine("WorkerThreadManager::ThreadCallBack - END");
}
/// <summary>
/// NT-Service like API... may be useful ;)
/// </summary>
public bool Start()
{
//
// I/O Synchro initalisation
//
_QueryStopEvent.Reset();
_StopCompletedEvent.Reset();
//
// Create & run thread
//
_InternalThread = new Thread(new ThreadStart(ThreadCallBack));
_InternalThread.Name = "WorkerThreadManagerThread";
_InternalThread.Start();
return true;
}
/// <summary>
/// NT-Service like API...
/// </summary>
public bool Stop()
{
//
// Query Stop
//
_QueryStopEvent.Set();
//
// Wait for stop ACK
//
_StopCompletedEvent.WaitOne(_TimeOut, false);
//
// Cleanup
//
_InternalThread = null;
return true;
}
}
}
|
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.