The WorkerThread Wrapper Class
The source code accompanying this book contains the WorkerThread class, which is a high-level wrapper class around the basic .NET Thread class. WorkerThread is defined as:
public class WorkerThread : IDisposable
{
public WorkerThread();
public WorkerThread(bool autoStart);
public int ManagedThreadId{get;}
public Thread Thread{get;}
public WaitHandle Handle{get;}
public void Start();
public void Dispose();
public void Kill();
public void Join();
public bool Join(int millisecondsTimeout);
public bool Join(TimeSpan timeout);
public string Name{get;set;}
public bool IsAlive{get;}
public void Dispose();
}
WorkerThread provides easy thread-creation and other features, including a Kill() method for terminating threads (instead of using Abort()). The potentially dangerous methods of the Thread class are not present in the interface of WorkerThread, but the good ones are maintained. WorkerThread also enforces the best practices of using .NET threads discussed so far. Example 8-15 shows the implementation of WorkerThread. Because the Thread class is sealed, I had to use containment rather than derivation when defining WorkerThread. WorkerThread has the m_ThreadObj member variable of type Thread, representing the underlying wrapped thread. You can access the underlying thread via the Thread property of WorkerThread, if you want to be able to do direct thread manipulation.
Example 8-15. The WorkerThread wrapper class
public class WorkerThread : IDisposable { ManualResetEvent ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access