2013-03-28 29 views
0

什麼是正確的Rx擴展方法(在.NET中)持續生成N秒的事件?Rx擴展可以持續生成N秒的事件嗎?

通過「保持生成事件N秒」我的意思是,這將保持自DateTime.Now直到DateTime.Now + TimeSpan.FromSeconds循環產生的事件(N)

我工作的遺傳算法這將產生大量假設,並將最成功的假設傳播給下一代。需要用一些優雅的方式來約束這個傢伙。

後來補充:

其實我已經意識到我需要做拉而不是推,來到-了這樣的事情:

public static class IEnumerableExtensions 
{ 
    public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, int? times = null) 
    { 
     if (times == null) 
      return enumerable.ToArray(); 
     else 
      return enumerable.Take(times.Value).ToArray(); 
    } 

    public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, TimeSpan timeout, int? times = null) 
    { 
     var start = DateTime.Now; 

     if (times != null) enumerable = enumerable.Take(times.Value); 

     using (var iterator = enumerable.GetEnumerator()) 
     { 
      while (DateTime.Now < start + timeout && iterator.MoveNext()) 
       yield return iterator.Current; 
     } 
    } 
} 

和使用將是:

var results = lazySource.SelectMany(item => 
{ 
    //processing goes here 
}).Pull(timeout: TimeSpan.FromSeconds(5), times: numberOfIterations); 

回答

4

有可能是這樣做的更清潔的方式,但你可以使用:

// This will generate events repeatedly 
var interval = Observable.Interval(...); 

// This will generate one event in N seconds 
var timer = Observable.Timer(TimeSpan.FromSeconds(N)); 

// This will combine the two, so that the interval stops when the timer 
// fires 
var joined = interval.TakeUntil(timer); 

這是一個很長的時間,因爲我做了任何的Rx,所以我道歉,如果這是不正確 - 但它是值得一試...

+0

喬恩像往常一樣在現場;您還可以使用Observable.Create製作自定義流。另外,如果在控制流上沒有信號超時窗口超時,超時也會拋出。 – JerKimball

+0

@JerKimball:啊,但如果原始流仍在生成,它不會拋出(並停止流)?在這種情況下,它不會很好... –

+0

由於答案可能是正確的 - 我突然意識到,在我的具體情況下,使用「拉」而不是「推」更好,因爲它感覺更自然不斷推動處理管道的假設,而不是推動訂閱。但你的回答肯定幫助我理解我真正想做的事情! – IlliakaillI

0

喬恩的職位是在相當多地方,但我注意到你的編輯你建議的地方你會創建你自己的擴展方法來做到這一點。如果你只是使用內建的運算符,我認爲它會更好。

//LinqPad sample 
void Main() 
{ 
    var interval = Observable.Interval(TimeSpan.FromMilliseconds(250)); 
    var maxTime = Observable.Timer(TimeSpan.FromSeconds(10)); 
    IEnumerable<int> lazySource = Enumerable.Range(0, 100); 

    lazySource.ToObservable() 
      .Zip(interval, (val, tick)=>val) 
      .TakeUntil(maxTime) 
      .Dump(); 
} 

*即。容易讓其他開發者保持和理解

相關問題