Stream pause pattern similar to CancellationTokenSource and CancellationToken?

I started using the collaboration reduction template introduced in the 4.0 framework, ConcellationTokenSource, and CancellationToken, and I found it very useful and simple.

My goal is now to provide my application with a similar elegant and simple solution, but to pause threads instead of canceling them. Since the request will also be different in this case from the listening command of the pause command, I thought that it would be nice to have something like PauseTokenSource and PauseToken. So my first question is if you offer such a template for joint suspension or if something is even better.

If you have a good idea to have such a template, do you have any suggestions or recommendations on how to do this? At the moment, I thought that the source should be able to pause and pause using ManualResetEvent and that the token should have a link to the source. This follows the first project, 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(); } } 
+6
source share
1 answer

Why not create an interface that can implement the PauseTokenSource, and send it instead of PauseTokens. Or what is the advantage of having tokens different from the source? I do not see...

 public interface IPauseToken { bool IsPausedRequested { get; } void WaitUntillPaused(); } 

And by the way, WaitUntillPaused, if it is not WaitWhilePaused ...

0
source

Source: https://habr.com/ru/post/886465/


All Articles