返回一个Stream对象和ObjectDisposedException。

huangapple go评论73阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月5日 18:46:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定