Saturday, May 30, 2009

"Extend" the thread class in C#

// just inherit from the EasyThread class and override the PerformWork method

public class EasyThread: IDisposable
{
Thread WorkerThread;

public EasyThread()
{
if (WorkerThread == null)
WorkerThread = new Thread(new ThreadStart(PerformWork));
}

public void Run()
{
if (WorkerThread.IsAlive == false)
WorkerThread.Start();

if (WorkerThread.ThreadState == ThreadState.Suspended)
WorkerThread.Resume();
}

///
/// EasyThread provides a facade to inheriting from a Thread class.
/// Override the perform work method to perform your tasks.
///

protected virtual void PerformWork()
{

}

public void Pause()
{
WorkerThread.Suspend();
}

public void Quit()
{
Cleanup();
}

private void Cleanup()
{
WorkerThread.Join(0);
WorkerThread = null;
}

public void Dispose()
{
Cleanup();
}
}

No comments:

Post a Comment