使用
Rx,我希望在以下代码中暂停和恢复功能:
如何实现Pause()和Resume()?
static IDisposable _subscription; static void Main(string[] args) { Subscribe(); Thread.Sleep(500); // Second value should not be shown after two seconds: Pause(); Thread.Sleep(5000); // Continue and show second value and beyond now: Resume(); } static void Subscribe() { var list = new List<int> { 1,2,3,4,5 }; var obs = list.ToObservable(); _subscription = obs.SubscribeOn(Scheduler.NewThread).Subscribe(p => { Console.WriteLine(p.ToString()); Thread.Sleep(2000); },err => Console.WriteLine("Error"),() => Console.WriteLine("Sequence Completed") ); } static void Pause() { // Pseudocode: //_subscription.Pause(); } static void Resume() { // Pseudocode: //_subscription.Resume(); }
Rx解决方案
>我相信我可以使用某种布尔字段门控和线程锁定(Monitor.Wait和Monitor.Pulse)
>但是有没有一个Rx运算符或其他一些反应速记来达到相同的目的?
解决方法
它只是工作:
class SimpleWaitPulse { static readonly object _locker = new object(); static bool _go; static void Main() { // The new thread will block new Thread (Work).Start(); // because _go==false. Console.ReadLine(); // Wait for user to hit Enter lock (_locker) // Let's now wake up the thread by { // setting _go=true and pulsing. _go = true; Monitor.Pulse (_locker); } } static void Work() { lock (_locker) while (!_go) Monitor.Wait (_locker); // Lock is released while we’re waiting Console.WriteLine ("Woken!!!"); } }