简体   繁体   English

反应式框架Hello World

[英]Reactive Framework Hello World

This is an easy program to introduce the Reactive Framework . 这是一个介绍Reactive Framework的简单程序 But I want to try the error handler, by modifying the program to be: 但我想通过修改程序来尝试错误处理程序:

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();

In this sample the follwing overload is used. 在此示例中,使用了以下过载。

public static IDisposable Subscribe<TSource>(
     this IObservable<TSource> source, 
     Action<TSource> onNext, 
     Action<Exception> onError, 
     Action onCompleted);

I hoped I would see the exception message printed, but the console application crashed. 我希望我会看到打印的异常消息,但控制台应用程序崩溃了。 What is the reason? 是什么原因?

The exception handler is used for exceptions created in the observable itself, not by the observer. 异常处理程序用于在observable本身中创建的异常,而不是由观察者创建的异常。

An easy way to provoke the exception handler is something like this: 激发异常处理程序的简单方法是这样的:

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");
    }
}

Output: 输出:

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

In the Rx library, any user code passed into an operator that works on IObservable (Select, Where, GroupBy etc...) will be caught and send to the OnError handler of observers subscribed to the observable. 在Rx库中,传入操作于IObservable(Select,Where,GroupBy等...)的运算符的任何用户代码都将被捕获并发送给订阅了observable的观察者的OnError处理程序。 The reason these are handled is that they are part of the computation. 处理这些的原因是它们是计算的一部分。

Exceptions occurring in Observer code will have to be handled by the user. Observer代码中出现的异常必须由用户处理。 As they're at the end of the computation, it is unclear to Rx how to handle these. 由于它们在计算结束时,Rx不清楚如何处理这些。

Does it really crash or jumps Visual Studio into and shows you that an exception happened? 它是否真的崩溃或跳转到Visual Studio并向您显示异常发生? If the second is true, you should take a look into Debug - Exception within the menu bar and deselect everything on the right. 如果第二个是真的,你应该看看菜单栏中的Debug - Exception并取消选择右边的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM