方法完成后重用流
我目前正在开发一个 C# 项目,该项目使用 FileStream 打开文件并将信息传递给 StreamReader 进行处理。
我想要做的是我有一个方法将流传递给另一个方法,该方法进行处理,一旦该方法完成,原始方法就会调用另一个方法,将其传递给相同的流。但是,当调用第二个方法时第一个流进程完成时,它会显示一个异常,表明线程不可读。
当我查看调试流时,当我查看有关流的详细信息时,它说它无法读取、查找或写入,并且流的长度参数说引发了 System.ObjectDisposeException 类型的异常。
问题是,如何在第一个方法完成后保持流可读,以便可以在第二个流中处理相同的流。
感谢您提供的任何帮助。
I am currently working on a C# project that uses a FileStream to open a file and passes the information to a StreamReader for it to be processed.
What I want to be able to do is I have a method which passes the stream to another method, that does the processing and once that method finishes, the original method calls another method passing it the same stream. However, when the first stream process completes when the second method is called it displays an exception saying that the thread is not readable.
When I look at debugging the stream, when I look at the details about the stream it says that it cannot be read, seek or write, and the length parameter of the stream says threw an exception of type System.ObjectDisposedException.
The question is, how can I keep the stream readable after the first method has completed so that the same stream can be processed in the second stream.
Thanks for any help you can provide.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的streamReader是“using”语句的一部分,它会在语句块的末尾处理文件流。
简单的解决方案是不显式处理 reader,将其留给 GC
[更多想法]
如果大多数方法都是通过 TextReader 接口访问文件流,则可以传递 reader 从而避免所有权问题。
if your streamReader is part of "using" statement, it disposes the file stream in the end of the statement block.
Simple solution is not to dispose the reader explicitly, leaving it to GC
[More thoughts]
If most of the methods are accessing file stream through TextReader interface, you can pass reader thus avoiding the problem with the ownership.
如果我理解正确的话,你的流关闭得太快了。根据您的说法,可能是因为您正在
关闭
或处置
StreamReader 根据文档,它将关闭底层流。尝试不关闭 StreamReader(不需要时忽略它)。
例如,如果您的代码如下所示:
您已在第一种方法中关闭了流。 你也会遇到同样的问题。
所以请确保不要做任何这些事情。
顺便说一句:在 C#5 中,我听说,如果您想在关闭基础流时关闭读取器/写入器,则读取器/写入器将被参数化(就像 CryptoStream 现在一样)
If I understood you correctly, your stream is getting closed too fast. Based on what you say, it might be because you are
Closing
orDisposing
StreamReader which, according to documentation, will close underlying stream.Try not closing
StreamReader
(just ignore it, after it's not needed).For example, if your code looks like this:
You have closed your stream in 1st method. You will have the same problem if you call:
So make sure aren't doing any of those things.
Btw: in C#5 I have heard, that Readers/Writers will be parametrized, if you want then to close underlying stream when they are closed (just like CryptoStream have right now)