2017-09-04 35 views
4

我正在寫一個小型記錄器,我想打開一次日誌文件,在日誌消息到達時繼續寫入,並在程序終止時處理所有內容。使用反應式編程寫入以打開FileStream

我不知道如何保持FileStream打開反應性地寫入消息到達。

我想從我以前的解決方案中更新設計,我的ConcurrentQueue充當緩衝區,並且使用隊列的using語句中的循環。

具體來說,我想同時利用using語句結構的,所以我沒有顯式地關閉流和作家,以及無功,無迴路的編程風格。目前,我只知道如何一次使用這些構造中的一個:或者是using /循環組合,或者是顯式流關閉/反應組合。

這裏是我的代碼:

BufferBlock<LogEntry> _buffer = new BufferBlock<LogEntry>(); 


    // CONSTRUCTOR 
    public DefaultLogger(string folder) 
    { 
     var filePath = Path.Combine(folder, $"{DateTime.Now.ToString("yyyy.MM.dd")}.log"); 

     _cancellation = new CancellationTokenSource(); 

     var observable = _buffer.AsObservable(); 

     using (var stream = File.Create(_filePath)) 
     using (var writer = new StreamWriter(stream)) 
     using (var subscription = observable.Subscribe(entry => 
            writer.Write(GetFormattedString(entry)))) 
     { 
      while (!_cancellation.IsCancellationRequested) 
      { 
       // what do I do here? 
      } 
     } 
    } 

回答

3

您需要使用Observable.Using。它旨在創建一個IDisposble資源,該資源在序列結束時處理。

嘗試這樣:

IDisposable subscription = 
    Observable.Using(() => File.Create(_filePath), 
     stream => Observable.Using(() => new StreamWriter(stream), 
      writer => _buffer.AsObservable().Select(entry => new { entry, writer }))) 
     .Subscribe(x => x.writer.Write(GetFormattedString(x.entry)));