2

我有一个 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用来做我想做的事,还是我需要一种完全不同的方法?

4

2 回答 2

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();
}
于 2013-01-04T14:59:10.293 回答
0

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

这是一件有趣的事情——说实话,我以前从来没有需要过这个,但是有一个可观察的扩展Observable.Synchronize

这使得阻塞变得非常简单,尽管我不是 100% 确定这将适用于您的用例......无论如何,这是使用这种方法的修改后的 main:

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();
}
于 2013-01-03T00:25:58.170 回答