Pausing/Resuming
.NET already supports suspending and resuming threads through the Thread.Suspend() and Thread.Resume() methods. However, the existing implementation only works well for threads that use no shared resources. Because the built-in methods are insufficient for most work items, a cooperative model must be used instead.
Again, the CheckState() method is used by a work item to determine the state of the work item thread. When the thread is in the Pausing state and CheckState() is called, the thread moves to the Paused state. The method then calls WaitOne() on the StateChanged event that is internal to the work item thread. This blocks the method until the state of the thread changes again. When the thread state changes, the block is released and CheckState() reevaluates the state of the thread. When the thread enters the Resuming state, it will be automatically transitioned back to the Running state prior to CheckState() returning. The net effect is that the thread is paused while in the Paused state.
By isolating the thread state management inside CheckState(), the work item is free from dealing with thread state requests. The simple algorithm previously described continues to work even with pause and resume requests. The only issue that a work item needs to handle when supporting pause requests is how to deal with shared resources.
Terminating Work Items
.NET already supports terminating a thread through the Thread.Abort() method. It should only be used when absolutely necessary to avoid leaving locks held or causing resource leaks.
Terminating and canceling a work item has the same effect. The difference lies in how it is done and the final state of the work item thread. When a work item is canceled, if it is supported, the work item's thread moves to the Canceling state. The next time CheckState() is called, the thread moves to the Canceled state and the method returns a false value terminating the work item.
For termination requests, the same thing occurs except the Terminating and Terminated states are used. However, the thread also enters the Terminated state if a ThreadAbortException is raised. Additionally, a work item can be terminated even if it does not support cancelation. Therefore, it is important that a work item always checks the return value from CheckState().
One enhancement that could be made to termination requests for work items is a timeout. If a work item fails to terminate (not cancel) in a specified period of time, then Thread.Abort() should be called to forcefully terminate the work item thread and work item.