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

How to return a Stream from a method, knowing it should be disposed?(如何从方法返回 Stream,知道它应该被处理?)
本文介绍了如何从方法返回 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,知道它应该被处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)