你能阻止 StreamReader 处理底层流吗? [英] Can you keep a StreamReader from disposing the underlying stream?
问题描述
有没有办法做到这一点:
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...
}
无需打开文件两次?
我似乎无法让 StreamReader 不处理我的流.我也不想让它超出范围.然后垃圾收集器最终会调用Dispose,杀死流.
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.
推荐答案
我也不想让它超出范围.然后垃圾收集器最终会调用Dispose,杀死流.
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.
垃圾收集器将调用 Finalize
方法(析构函数),而不是 Dispose
方法.终结器将调用 Dispose(false)
,后者将不处置底层流.如果您需要直接使用底层流,您应该可以让 StreamReader
超出范围.只要确保在适当的时候手动处理底层流即可.
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屋!