Reactive Rx 2.0 EventLoopScheduler ObjectDisposedException after dispose

后端 未结 3 1340
無奈伤痛
無奈伤痛 2021-01-06 11:15

I\'m using Rx 2.0\'s EventLoopScheduler to queue up / serialize work. When I need to dispose the scheduler, if there is remaining work, I will receive an unhandled ObjectDis

相关标签:
3条回答
  • 2021-01-06 11:37

    Yeah, I've seen that before as well - I don't think there's a way to "flush out the event thread" per se, but you can do something like this:

    EventLoopScheduler scheduler = new EventLoopScheduler();
    var wrappedScheduler = scheduler.Catch<Exception>((ex) => 
    {
        Console.WriteLine("Got an exception:" + ex.ToString());
        return true;
    });
    
    for (int i = 0; i < 100; ++i)
    {
        var handle = Observable.Interval(TimeSpan.FromMilliseconds(1))
                               .ObserveOn(wrappedScheduler)
                               .Subscribe(Observer.Create<long>((x) => Thread.Sleep(1000)));
    
        handles.Add(handle);
    }
    
    0 讨论(0)
  • 2021-01-06 11:45

    Actually, there is a simple way to flush the EventLoopScheduler queue before disposing. First, make sure that all subscriptions that are adding actions to the queue are disposed, so that nothing else can be added.

    Then, simply schedule the dispose of the scheduler itself:

    scheduler.Schedule(() =>
    {
        // cleanup code: dispose of other stuff here
        scheduler.Dispose();
    });
    

    This last scheduled action is ensured to run after all other pending actions have run and shutsdown the thread.

    0 讨论(0)
  • 2021-01-06 11:51

    It's not that there is work remaining (i.e. the scheduler still has things in its queue), it's that you still have Subscriptions outstanding that are trying to add stuff to that queue.

    Dispose all of the Subscriptions and then dispose the Scheduler, and it should work correctly

    0 讨论(0)
提交回复
热议问题