英文:
Returning a Stream object and ObjectDisposedException
问题
在C#代码中,我观察到在一个ASP.NET应用程序中发生了ObjectDisposedException
异常,并且在中间件中有一个通用的错误处理程序,但由于消息中缺少详细信息,我无法捕获到被关闭的文件。消息看起来总是相同的:"System.ObjectDisposedException: 无法访问已处理的对象。"
顺便说一下,没有关于错误来源的详细信息,使用这种方式(在通用管道中处理错误)似乎有点... 令人沮丧,至少是这样。不管怎样:
我猜测引发异常的文件操作与我的更改有关。(真是丢脸。)幸运的是,更改的量并不是很大。我的候选对象是从using
语句内部返回的Stream对象。
public Stream GetStream(string path)
{
using (var fileStream = File.Open(path, FileMode.Open))
{
return fileStream;
}
}
为什么会引发这个异常?
英文:
In C# code, I observed the ObjectDisposedException
's occurrence in an ASP.NET application and its generic error handler in a middleware, but because of missing details in the message I was not able to catch the closed file mentioned. The message looks always the same: "System.ObjectDisposedException: Cannot access a disposed object.".
BTW, without details about the source of error, this technique (of handling error in a common pipe) seems to be a little... frustrating, at least. Anyway:
I guessed the file operation causing the exception was related to my changes. (Shame.) Fortunately, it was not so much volume of changes. My candidate was a Stream object returned from inside of using
statement.
public Stream GetStream(string path)
{
using (var fileStream = File.Open(path, FileMode.Open))
{
return fileStream;
}
}
Why this exception was raised?
答案1
得分: 1
以下是翻译好的部分:
"The code from the question is not correct - if I return the stream, the outer code should be responsible for disposing it. The correct version should look like this:
public Stream GetStream(string path)
{
return File.Open(path, FileMode.Open);
}
Thanks to the commenters."
英文:
The code from the question is not correct - if I return the stream, the outer code should be responsible for disposing it. The correct version should look like this:
public Stream GetStream(string path)
{
return File.Open(path, FileMode.Open);
}
Thanks to the commenters.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论