问题描述
我有一个采用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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!