2013-08-24 35 views
0

我在閱讀IntroToRx,我在示例代碼中遇到了一些問題。這裏是總和我的代碼:反應性擴展:爲什麼這會立即退出?

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()序列。

但是,當我運行代碼時,我所得到的只是最後的「完成」。沒有數字,沒有「完成」,只有「完成」。

我在這裏做錯了什麼?

回答

2

我假設你沒有耐心等待5秒鐘,否則你會看到代碼工作。

Rx一起記住的主要想法是,Observable.Subscribe將幾乎立即返回控制到調用方法。換句話說,Observable.Subscribe不會阻止,直到結果產生。因此對Console.WriteLine的呼叫只會在五秒後被調用。

+0

這並不是說我缺乏耐心;相反,我認爲除非順序已經完成,否則「完成」將不會顯示,例如,從來沒有在這個例子。我理解的根本缺陷。 –

+0

我很擔心我已經爲Done條款和Completed做了一個例子。如果您將「已完成」這個單詞換成「已完成」,那麼您的程序會更準確。理想情況下也捕獲訂閱,然後將其置於'ReadKey()'之後。 –

0

你需要一些方法讓主線程等待你正在做的事情。您可以使用一個信號,如果你喜歡

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) 
    { 
     SemaphoreSlim ss = new SemaphoreSlim(1); 
     var observable = Observable.Interval(TimeSpan.FromSeconds(5)); 
     observable.Subscribe(
      Console.WriteLine, 
     () => { 
       Console.WriteLine("Completed"); 
       ss.Release(); 
      } 
     ); 
     ss.Wait(); 
     Console.WriteLine("Done"); 
     Console.ReadKey(); 
    } 

    } 
} 

雖然可能在這種情況下,只是爲了更好地寫

static void Main(string[] args) 
    { 
     SemaphoreSlim ss = new SemaphoreSlim(1); 
     Observable.Interval(TimeSpan.FromSeconds(5)).Wait(); 
     Console.WriteLine("Completed"); 
     Console.WriteLine("Done"); 
     Console.ReadKey(); 
    } 
+0

我認爲你不應該在這樣一個簡單的例子中使用原始的等待句柄和Rx。海事組織,這樣做會破壞學習Rx的觀點。 –

+0

你必須在main中使用wait。您不能將其標記爲異步並使用等待。 – bradgonesurfing