A pattern for pausing threads similar to the CancellationTokenSource and CancellationToken pattern?
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 IsPau开发者_开发技巧seRequested
{
get { return source != null && source.IsPauseRequested; }
}
public void WaitUntillPaused()
{
if (source != null)
source.WaitUntillPaused();
}
}
Why not make an interface that PauseTokenSource can implement, and send it around instead of PauseTokens. Or what's the benefit of having token instances other than the source? I don't see any...
public interface IPauseToken
{
bool IsPausedRequested { get; }
void WaitUntillPaused();
}
And by the way, WaitUntillPaused, should it not be WaitWhilePaused...
精彩评论