强制关闭流
我时常遇到问题,我的程序中有一些 StreamReader
和 StreamWriter
读取信息并写入信息。它们在大约 99% 的情况下都是正确的,但偶尔我会在一段我运行了多次的代码上得到一个无法关闭的 StreamWriter
。
如果我向某个功能发送垃圾邮件,这种情况往往会发生,但我正在尝试找到一种安全的方法来保证蒸汽得到处理。有人知道怎么做吗?
I have an issue from time to time, I have a few StreamReader
s and StreamWriter
s in my program that read info and write it. They go right about 99% of the time, but once in a while I end up with a StreamWriter
that won't close, on a piece of code I've run multiple times.
This tends to happen if I spam a function, but I am trying to find a safe way to guarantee a steam disposed. Anyone know how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
using
语句 MSDN这可能很有用:
关闭流读取和流写入器表单退出
您也可以使用
Try
块try a
using
statement MSDNthis can be useful:
Closing Stream Read and Stream Writer when the form exits
Also you could use a
Try
Block如果流的范围是本地的,请始终使用以下构造:
另一方面,如果您将流用作类字段,则实现
IDisposable
模式并在处置类时处置您的流对象:< a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow">IDisposableIf the stream's scope is local, always use the following construct:
If on the other hand you are using the stream as a class field then implement the
IDisposable
pattern and dispose your stream objects when disposing your class: IDisposable将 StreamWriter 包装在 using 语句中是我通常确保它被处置的方式。
另一种方法是使用
finally
块。Wrapping the StreamWriter in a using statement is how I usually ensure it is disposed of.
An alternative would be to use a
finally
block.