c# – 在冷IObservable上暂停并恢复订阅

前端之家收集整理的这篇文章主要介绍了c# – 在冷IObservable上暂停并恢复订阅前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用 Rx,我希望在以下代码中暂停和恢复功能

如何实现Pause()和Resume()?

  1. static IDisposable _subscription;
  2.  
  3. static void Main(string[] args)
  4. {
  5. Subscribe();
  6. Thread.Sleep(500);
  7. // Second value should not be shown after two seconds:
  8. Pause();
  9. Thread.Sleep(5000);
  10. // Continue and show second value and beyond now:
  11. Resume();
  12. }
  13.  
  14. static void Subscribe()
  15. {
  16. var list = new List<int> { 1,2,3,4,5 };
  17. var obs = list.ToObservable();
  18. _subscription = obs.SubscribeOn(Scheduler.NewThread).Subscribe(p =>
  19. {
  20. Console.WriteLine(p.ToString());
  21. Thread.Sleep(2000);
  22. },err => Console.WriteLine("Error"),() => Console.WriteLine("Sequence Completed")
  23. );
  24. }
  25.  
  26. static void Pause()
  27. {
  28. // Pseudocode:
  29. //_subscription.Pause();
  30. }
  31.  
  32. static void Resume()
  33. {
  34. // Pseudocode:
  35. //_subscription.Resume();
  36. }

Rx解决方

>我相信我可以使用某种布尔字段门控和线程锁定(Monitor.Wait和Monitor.Pulse)
>但是有没有一个Rx运算符或其他一些反应速记来达到相同的目的?

解决方法

它只是工作:
  1. class SimpleWaitPulse
  2. {
  3. static readonly object _locker = new object();
  4. static bool _go;
  5.  
  6. static void Main()
  7. { // The new thread will block
  8. new Thread (Work).Start(); // because _go==false.
  9.  
  10. Console.ReadLine(); // Wait for user to hit Enter
  11.  
  12. lock (_locker) // Let's now wake up the thread by
  13. { // setting _go=true and pulsing.
  14. _go = true;
  15. Monitor.Pulse (_locker);
  16. }
  17. }
  18.  
  19. static void Work()
  20. {
  21. lock (_locker)
  22. while (!_go)
  23. Monitor.Wait (_locker); // Lock is released while we’re waiting
  24.  
  25. Console.WriteLine ("Woken!!!");
  26. }
  27. }

详情请参阅How to Use Wait and Pulse

猜你在找的C#相关文章