Reactive Extensions:为什么会立即退出? [英] Reactive Extensions: Why does this exit immediately?

查看:44
本文介绍了Reactive Extensions:为什么会立即退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 IntroToRx 并且我在使用示例代码时遇到了一些问题.这是我的代码的总和:

I am reading IntroToRx and I'm having a bit of trouble with the sample code. Here is the sum total of my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LearningReactiveExtensions
{
  public class Program
  {
    static void Main(string[] args)
    {
        var observable = Observable.Interval(TimeSpan.FromSeconds(5));
        observable.Subscribe(
          Console.WriteLine, 
          () => Console.WriteLine("Completed")
        );
        Console.WriteLine("Done");
        Console.ReadKey();
    }

  }
}

如果我对这本书的理解正确,这应该向控制台写入一个数字序列,每五秒一次永远,因为我从来没有Dispose()这个序列.

If I understand the book correctly, this should write a sequence of numbers to the console, once every five seconds forever since I never Dispose() of the sequence.

然而,当我运行代码时,我得到的只是最后的完成".没有数字,没有完成",只有完成".

However, when I run the code, all I get is the "Done" at the end. No numbers, no "completed", nothing but "Done".

我在这里做错了什么?

推荐答案

我假设您没有耐心等待 5 秒过去,否则您会看到代码正在运行.

I am assuming you haven't had the patience to wait for 5 seconds to elapse otherwise you would have seen that the code is working.

Rx 的主要思想是Observable.Subscribe 几乎立即将控制权返回给调用方法.换句话说,Observable.Subscribe 在产生结果之前不会阻塞.因此对 Console.WriteLine 的调用只会在 5 秒后调用.

The main idea to keep in mind with Rx is that Observable.Subscribe will return control to calling method almost immediately. In other words, Observable.Subscribe does not block until the results are produced. Thus the call to Console.WriteLine will be invoked only after five seconds.

这篇关于Reactive Extensions:为什么会立即退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆