使用'yield return'观察异步序列

时间:2012-02-03 17:03:13

标签: c# .net system.reactive observable

以下示例正常工作:

static IEnumerable<int> GenerateNum(int sequenceLength)
    {
      for(int i = 0; i < sequenceLength; i++)
      {
          yield return i;
      }
    }

static void Main(string[] args)
    {

        //var observ = Observable.Start(() => GenerateNum(1000));
        var observ = GenerateNum(1000).ToObservable();

        observ.Subscribe(
            (x) => Console.WriteLine("test:" + x),
            (Exception ex) => Console.WriteLine("Error received from source: {0}.", ex.Message),
            () => Console.WriteLine("End of sequence.")
            );

        Console.ReadKey();
    }

然而,我真正想要的是使用注释掉的行 - 即我想异步运行'数字生成器',每次它产生一个新值,我希望它输出到控制台。它似乎不起作用 - 如何修改此代码才能工作?

1 个答案:

答案 0 :(得分:7)

在控制台应用程序中执行此操作以进行异步执行时,您可能希望使用ToObservable(IEnumerable<TSource>, IScheduler)重载(请参阅Observable.ToObservable Method (IEnumerable, IScheduler))。例如,要使用内置线程池计划,请尝试

var observ = GenerateNum(1000).ToObservable(Scheduler.ThreadPool);

它对我有用......为了扩展,以下完整的示例与我想要的想想完全相同:

    static Random r = new Random();

    static void Main(string[] args) {

        var observ = GenerateNum(1000).ToObservable(Scheduler.ThreadPool );

        observ.Subscribe(
            (x) => Console.WriteLine("test:" + x),
            (Exception ex) => Console.WriteLine("Error received from source: {0}.", ex.Message),
            () => Console.WriteLine("End of sequence.")
            );

        while (Console.ReadKey(true).Key != ConsoleKey.Escape) {
            Console.WriteLine("You pressed a key.");
        }
    } 

    static IEnumerable<int> GenerateNum(int sequenceLength) {
        for (int i = 0; i < sequenceLength; i++) {
            Thread.Sleep(r.Next(1, 200));
            yield return i;
        }
    }