在使用SubscribedOn之后控制Rx订阅的线程

时间:2013-01-03 00:17:00

标签: c# system.reactive

我有一个Rx订阅我SubscribeOn使用不同的线程来防止它被阻止。但是,由于资源管理问题,我希望处理该订阅。我无法弄清楚如何在控制台应用程序或winforms应用程序(我有两个用例)的上下文中完成此操作。下面是一个简化案例的工作代码,模拟我正在做的事情:

internal class Program
{

    private static void Log(string msg)
    {
        Console.WriteLine("[{0}] " + msg, Thread.CurrentThread.ManagedThreadId.ToString());
    }

    private static void Main(string[] args)
    {

        var foo = Observable.Create<long>(obs =>
            {
                Log("Subscribing starting.. this will take a few seconds..");
                Thread.Sleep(TimeSpan.FromSeconds(2));
                var sub =
                    Observable.Interval(TimeSpan.FromSeconds(1))
                              .Do(_ => Log("I am polling..."))
                              .Subscribe(obs);
                return Disposable.Create(() =>
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(3));
                        sub.Dispose();
                        Log("Disposing is really done now!");
                    });
            });

        Log("I am subscribing..");
        var disp = foo.SubscribeOn(NewThreadScheduler.Default).Subscribe(i => Log("Processing " + i.ToString()));
        Log("I have returned from subscribing...");

        // SC.Current is null in a ConsoleApp :/  Can I get a SC that uses my current thread?
        //var dispSynced = new ContextDisposable(SynchronizationContext.Current, disp);
        Thread.Sleep(TimeSpan.FromSeconds(5));
        Log("I'm going to dispose...");
        //dispSynced.Dispose();
        disp.Dispose();
        Log("Disposed has returned...");
        Console.ReadKey();
    }
}

当上述情况发生时,我得到:

[10] I am subscribing..
[10] I have returned from subscribing...
[11] Subscribing starting.. this will take a few seconds..
[6] I am polling...
[6] Processing 0
[6] I am polling...
[6] Processing 1
[10] I'm going to dispose...
[10] Disposed has returned...
[13] I am polling...
[6] I am polling...
[13] I am polling...
[14] Disposing is really done now!

所以,我试图做的就是让[10] Disposed has returned...成为打印的最后一行,表明Dispose调用正在阻塞。

Rx附带的ContextDisposable似乎非常适合我的用例,但我不知道如何获得代表我当前线程的SynchronizationContext。有没有办法让ContextDisposable做我想做或做的事我需要一种完全不同的方法?

2 个答案:

答案 0 :(得分:2)

如果查看SubscribeOn的源代码,看起来就像在指定的调度程序上调度dispose函数一样。尝试这样的事情:

private static IObservable<long> GetObservable(IScheduler scheduler)
{
  return Observable.Create<long>(obs =>
  {
    var disposables = new CompositeDisposable();

    disposables.Add(
      Disposable.Create(() =>
      {
        Thread.Sleep(TimeSpan.FromSeconds(3));
        Log("Disposing is really done now!");
      }));

    disposables.Add(
      scheduler.Schedule(() =>
      {
        Log("Subscribing starting.. this will take a few seconds..");
        Thread.Sleep(TimeSpan.FromSeconds(2));
        disposables.Add(
          Observable.Interval(TimeSpan.FromSeconds(1)).Do(_ => Log("I am polling...")).Subscribe(obs));
      }));

    return disposables;
  });


private static void Main(string[] args)
{
  var foo = GetObservable(NewThreadScheduler.Default);

  Log("I am subscribing..");
  var disp = foo.Subscribe(i => Log("Processing " + i.ToString()));
  Log("I have returned from subscribing...");

  // SC.Current is null in a ConsoleApp :/  Can I get a SC that uses my current thread?
  //var dispSynced = new ContextDisposable(SynchronizationContext.Current, disp);
  Thread.Sleep(TimeSpan.FromSeconds(5));
  Log("I'm going to dispose...");
  //dispSynced.Dispose();
  disp.Dispose();
  Log("Disposed has returned...");
  Console.ReadKey();
}

答案 1 :(得分:0)

(从头开始 - 还有另一种方式!)

这是一个值得关注的事情 - 事实上,我以前从未有过这方面的需要,但有一个可观察的延伸Observable.Synchronize

这使得阻塞非常简单,虽然我不是100%确定这将适用于您的用例...无论如何,这是使用这种方法的修改主体:

private static void Main(string[] args)
{
    var sync = new object();
    var foo = Observable.CreateWithDisposable<long>(obs =>
    {
        Log("Subscribing starting.. this will take a few seconds..");
        Thread.Sleep(TimeSpan.FromSeconds(2));
        var sub = Observable.Interval(TimeSpan.FromSeconds(1))
                        .Do(_ => Log("I am polling..."))
                        .Synchronize(sync)
                        .Subscribe(obs);
        return Disposable.Create(
            () =>
                {
                    lock (sync)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(3));
                        sub.Dispose();
                        Log("Disposing is really done now!");                                
                    }
                });
    });

    Log("I am subscribing..");
    var disp = foo
        .SubscribeOn(Scheduler.NewThread)
        .Subscribe(i => Log("Processing " + i));

    Log("I have returned from subscribing...");
    Thread.Sleep(TimeSpan.FromSeconds(5));
    Log("I'm going to dispose...");
    disp.Dispose();
    Log("Disposed has returned...");
    Console.ReadKey();
}