用户登录
用户注册

分享至

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

  • 作者: 开水泡泡
  • 来源: 51数据库
  • 2023-02-13

问题描述

我有一个将 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);
软件
前端设计
程序设计
Java相关