2017-09-04 112 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)));