暂停和冷的IObservable恢复认购 [英] Pause and Resume Subscription on cold IObservable

查看:92
本文介绍了暂停和冷的IObservable恢复认购的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用接收,我希望暂停和恢复功能在以下code:

Using Rx, I desire pause and resume functionality in the following code:

    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();
    }

接收解决方案?


  • 我相信我可以使它具有某种布尔字段与门螺纹锁固(联合工作 Monitor.Wait 监视器。脉冲

    但有一个接收运营商或其他一些反应简写来达到同样的目的?

    But is there an Rx operator or some other reactive shorthand to achieve the same aim?

    推荐答案

    这只是工作:

        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!!!");
          }
        }
    

    请,请参阅如何使用等待和脉冲了解更多详情

    Please, see How to Use Wait and Pulse for more details

    这篇关于暂停和冷的IObservable恢复认购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆