[英]How to loop Observable Rx until condition met?
我發現這個很好的答案與我要解決的問題非常相似:
我第一次使用這個 System.Reactive package 雖然所以我在使用和語法上苦苦掙扎。 我正在嘗試修改此塊以滿足我的需要:
var processExited =
// Observable will tick when the process has gracefully exited.
Observable.FromEventPattern<EventArgs>(process, nameof(Process.Exited))
// First two lines to tick true when the process has gracefully exited and false when it has timed out.
.Select(_ => true)
.Timeout(TimeSpan.FromMilliseconds(processTimeOutMilliseconds), Observable.Return(false))
// Force termination when the process timed out
.Do(exitedSuccessfully => { if (!exitedSuccessfully) { try { process.Kill(); } catch {} } } );
我希望它在超時時檢查 stdOut 緩沖區中的特定字符串,如果找到它則退出,否則繼續直到下一次超時。 而且,我只想在我“放棄”並終止進程之前做這么多超時,所以在循環中,如果它不退出,我會增加一個計數器並檢查它。 感謝您的幫助
添加說明,我想要這樣的東西:
int timeoutCount = 0;
const int maxTimeoutCount =5;
然后在 observable 中,類似.Do(exitedSuccessfully => {
if (!exitedSuccessfully) {
try {
if (timeoutCount >= maxTimeOutCount || output.ToString().Contains("string_i-m_looking_for_in_output_to_trigger_exit")) {
process.Kill();
}
timeOutCount++;
}
catch { }
}
反應式的基本設計理念是避免外部 state - 並以聲明方式表達行為。 在 Rx 中,您可能需要 model 傳統上以不同方式變異 state。
將進程作為可觀察對象的慣用方法是將進程的生命周期鏈接到對可觀察對象的訂閱。 訂閱啟動進程,取消訂閱停止進程,反之亦然,正常退出的進程完成了 observable。
我已經在Github 上實現了這個 model 。 它是 C# 和 F# 的單個文件庫,它將進程的標准輸入/輸出抽象為可觀察的。
使用 model:
StdioObservable
.Create("process.exe")
.TakeUntil(line => line.Contains("Done")) // unsub when you match
.Timeout(TimeSpan.FromSeconds(30)) // no output for 30 seconds
.Catch((Exception exn) => Observable.Empty<string>()) //handle timeout or other
.Subscribe();
如果您想在一段時間內終止該進程,盡管它會產生一些 output,請改用 .Take .Take(TimeSpan.FromSeconds(30))
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.