你好,我尝试了101个Rx示例中的一个:
static IEnumerable<int> GenerateAlternatingFastAndSlowEvents()
{
int i = 0;
while (true)
{
if (i > 1000)
{
yield break;
}
yield return i;
Thread.Sleep(i++ % 10 < 5 ? 500 : 1000);
}
}
private static void Main()
{
var observable = GenerateAlternatingFastAndSlowEvents().ToObservable().Timestamp();
var throttled = observable.Throttle(TimeSpan.FromMilliseconds(750));
using (throttled.Subscribe(x => Console.WriteLine("{0}: {1}", x.Value, x.Timestamp)))
{
Console.WriteLine("Press any key to unsubscribe");
Console.ReadKey();
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
我不明白为什么“按任意键取消订阅”这行文字从未显示。我的理解是订阅是异步的,你订阅后它会立即返回。是什么导致我的主线程阻塞了?
SubscribeOn(Scheduler.ThreadPool)
,订阅和观察者将在新线程上运行,因此Subscribe
方法会立即返回,您将看到您的消息。只有当您的可观察对象使用CurrentThread
调度程序进行调度时,您的Subscribe
方法和观察者才会在当前线程上运行。 - Enigmativity