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