I started using the cooperative thread cancellation pattern provided in framework 4.0 by ConcellationTokenSource and CancellationToken and I found it very useful and simple.
My purpose is now to provide to my application a similar elegant and simple solution but for pausing the threads instead of cancelling them. Since also in this case the requesting would be different from the listening to the pause command, I thought that having something like a PauseTokenSource and a PauseToken would be good. So my first question is if you suggest such a pattern for cooperative pausing or if it's better something else.
If it's a good idea to have such a pattern, do you have any suggestions or guidelines on how to do it? At the moment I thought that the source should be able to pause and unpause by a ManualResetEvent and that the token should have a reference to the source. It follows a first draft on which I hope you can give me suggestions for improving it.
public class PauseTokenSource
{
protected ManualResetEvent mre = new ManualResetEvent(true);
object syncRoot = new object();
public PauseToken PauseToken { get { return new PauseToken(this); } }
public bool IsPauseRequested { get { return !mre.WaitOne(0); } }
public void Pause()
{
mre.Reset();
}
public void UnPause()
{
mre.Set();
}
public void WaitUntillPaused()
{
mre.WaitOne();
}
}
public class PauseToken
{
private PauseTokenSource source;
public PauseToken(PauseTokenSource source)
{
this.source = source;
}
public bool IsPauseRequested
{
get { return source != null && source.IsPauseRequested; }
}
public void WaitUntillPaused()
{
if (source != null)
source.WaitUntillPaused();
}
}