如何从方法返回 Stream,知道它应该被处理?

时间:2023-03-09
本文介绍了如何从方法返回 Stream,知道它应该被处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将 FileStream 作为输入的方法.此方法在 for 循环内运行.

I have a method that takes FileStream as input. This method is running inside a for loop.

private void UploadFile(FileStream fileStream)
{
    var stream = GetFileStream();
    // do things with stream
}

我有另一种方法可以创建并返回 FileStream:

I have another method which creates and returns the FileStream:

private FileStream GetFileStream()
{
    using(FileStream fileStream = File.Open(myFile, FileMode.Open))
    {
        //Do something
        return fileStream;
    }
}

现在,当我尝试访问返回的 FileStream 时,第一个方法抛出一个 ObjectDisposedException,可能是因为它已经关闭,因为我正在使用using"来正确处理流.

Now the first method throws an ObjectDisposedException when I try to access the returned FileStream, probably because it is already closed since I am using "using" to properly dispose the stream.

如果我不使用using"而是按如下方式使用它,则 FileStream 保持打开状态,并且循环的下一次迭代(对同一文件进行操作)会抛出一个异常,告知该文件已在使用中:

If I don't use "using" and instead use it as follows, then the FileStream remains open and the next iteration of the loop (operating on the same file) throws an exception telling the file is already in use:

private FileStream GetFileStream()
{
    FileStream fileStream = File.Open(myFile, FileMode.Open);
    //Do something
    return fileStream;
}

如果我使用 try-finally 块,在其中关闭 finally 中的流,那么它也会抛出 ObjectDisposedException.

If I use a try-finally block, where I close the stream in the finally then it also throws the ObjectDisposedException.

如何有效地返回文件流并关闭它?

How to effectively return file stream and close it?

推荐答案

当您从方法返回 IDisposable 时,您将处理它的责任交给了调用者.因此,您需要在整个流的使用范围内声明您的 using 块,在您的情况下,这可能跨越了 UploadFile 调用.

When you return an IDisposable from a method, you are relegating the responsibility of disposing it to your caller. Thus, you need to declare your using block around the entire usage of the stream, which in your case presumably spans the UploadFile call.

using (var s = GetFileStream())
    UploadFile(s);

这篇关于如何从方法返回 Stream,知道它应该被处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:.NET 流,在对象之间传递流,最佳实践 (C#) 下一篇:使用 TcpClient 和 Reactive Extensions 从 Stream 读取连续

相关文章

最新文章