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

前端之家收集整理的这篇文章主要介绍了c# – 在冷IObservable上暂停并恢复订阅前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用 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!!!");
      }
    }

详情请参阅How to Use Wait and Pulse

猜你在找的C#相关文章