反应式框架Hello World

Che*_*hen 3 .net c# reactive-programming system.reactive

这是一个介绍Reactive Framework的简单程序.但我想通过修改程序来尝试错误处理程序:

var cookiePieces = Observable.Range(1, 10);
cookiePieces.Subscribe(x =>
   {
      Console.WriteLine("{0}! {0} pieces of cookie!", x);
      throw new Exception();  // newly added by myself
   },
      ex => Console.WriteLine("the exception message..."),
      () => Console.WriteLine("Ah! Ah! Ah! Ah!"));
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

在此示例中,使用了以下过载.

public static IDisposable Subscribe<TSource>(
     this IObservable<TSource> source, 
     Action<TSource> onNext, 
     Action<Exception> onError, 
     Action onCompleted);
Run Code Online (Sandbox Code Playgroud)

我希望我会看到打印的异常消息,但控制台应用程序崩溃了.是什么原因?

Jon*_*eet 5

异常处理程序用于在observable本身中创建的异常,而不是由观察者创建的异常.

激发异常处理程序的简单方法是这样的:

using System;
using System.Linq;

class Test
{
    static void Main(string[] args)
    {
        var xs = Observable.Range(1, 10)
                           .Select(x => 10 / (5 - x));

        xs.Subscribe(x => Console.WriteLine("Received {0}", x),
                     ex => Console.WriteLine("Bang! {0}", ex),
                     () => Console.WriteLine("Done"));

        Console.WriteLine("App ending normally");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Received 2
Received 3
Received 5
Received 10
Bang! System.DivideByZeroException: Attempted to divide by zero.
   at Test.<Main>b__0(Int32 x)
   at System.Linq.Observable.<>c__DisplayClass35a`2.<>c__DisplayClass35c.<Select
>b__359(TSource x)
App ending normally
Run Code Online (Sandbox Code Playgroud)