你可以从处置底层流保持一个StreamReader? [英] Can you keep a StreamReader from disposing the underlying stream?

查看:146
本文介绍了你可以从处置底层流保持一个StreamReader?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做到这一点:

  this.logFile = File.Open(what_r_u_doing.log,FileMode.OpenOrCreate,FileAccess.ReadWrite);使用(VAR SR =新的StreamReader(this.logFile))
{
    //读取数据
}// ...后来在类...this.logFile = File.Open(what_r_u_doing.log,FileMode.OpenOrCreate,FileAccess.ReadWrite);使用(VAR SW =新的StreamWriter(this.logFile))
{
    //其他数据写入了...
}

而无需打开文件两次?

我似乎无法使StreamReader的未处置我流。我不想就让它走出去的范围,无论是。那么垃圾回收器最终会调用Dispose,查杀流。


解决方案

  

我不想就让它走出去的范围,无论是。那么垃圾回收器最终会调用Dispose,查杀流。


垃圾收集器会调用敲定方法(析构函数),而不是的Dispose 方法。终结将调用的Dispose(假)这将不可以处理底层流。你应该留OK了的StreamReader 走出去的范围,如果你需要直接使用底层流。只要确保你手动处理底层流时,它的合适的。

Is there a way to do this:

this.logFile = File.Open("what_r_u_doing.log", FileMode.OpenOrCreate, FileAccess.ReadWrite);

using(var sr = new StreamReader(this.logFile))
{
    // Read the data in
}

// ... later on in the class ...

this.logFile = File.Open("what_r_u_doing.log", FileMode.OpenOrCreate, FileAccess.ReadWrite);

using(var sw = new StreamWriter(this.logFile))
{
    // Write additional data out...
}

Without having to open the file twice?

I can't seem to make the StreamReader not-dispose my stream. I don't want to just let it go out of scope, either. Then the garbage collector will eventually call the Dispose, killing the stream.

解决方案

I don't want to just let it go out of scope, either. Then the garbage collector will eventually call the Dispose, killing the stream.

Garbage collector will call the Finalize method (destructor), not the Dispose method. The finalizer will call Dispose(false) which will not dispose the underlying stream. You should be OK by leaving the StreamReader go out of scope if you need to use the underlying stream directly. Just make sure you dispose the underlying stream manually when it's appropriate.

这篇关于你可以从处置底层流保持一个StreamReader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆