如何从方法返回 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);
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源









