从using块中返回时

时间:2018-10-24 11:00:17

标签: c# .net

查看msdn处的using语句时,它表示以下内容:

  

当IDisposable对象的生存期限于单个方法时,应在using语句中声明并实例化它。 using语句以正确的方式在对象上调用Dispose方法,并且(如前所述,当您使用它时)它还会导致对象本身在调用Dispose时就超出范围。在using块中,该对象为只读对象,无法修改或重新分配。

考虑到MSDN提供的信息。 从使用方法已变为静态的using块中返回内存流时。

问:内存流在返回时会被处置还是关闭并作为只读内存流生存?

下面的代码用于返回内存流。

        public static MemoryStream CreatePermitFileMemoryStream(int encOnlineId)
        {
            var folder = @"path\anotherpath\filelocation";
            try
            {
                using (var zipStream = new MemoryStream())
                {
                    using (var fileStream = new FileStream(@"path\anotherpath\filelocation\file.zip", FileMode.OpenOrCreate))
                    {
                        using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create))
                        {
                            foreach (var fileInfo in Directory.EnumerateFileSystemEntries(folder))
                            {
                                if (fileInfo.Contains("file.tmp") || fileInfo.Contains("PERM.TXT"))
                                {
                                    var filename = new FileInfo(fileInfo);
                                    zipArchive.CreateEntryFromFile(fileInfo, filename.Name);
                                }
                            }
                            fileStream.CopyTo(zipStream);
                            zipStream.Position = 0;
                            return zipStream;
                        }
                    }
                }
            }
            finally
            {
                FileUtils.DeleteFile(@"path\anotherpath\filelocation");
            }

        }
        return new MemoryStream();
    }

3 个答案:

答案 0 :(得分:4)

The code may work because Dispose on a MemoryStream doesn't really do anything (the memory is reclaimed by GC), but I certainly wouldn't depend on it always doing so for all .NET implementations - unless the only function you're calling is GetBuffer(), which is guaranteed to work after closing the stream. It's probably safer to remove the 'using' in this case. The "read-only" refers to the inability to re-assign the reference to another object. BTW if you look at https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/MemoryStream.cs the comments in Dispose() indicate that the developers deliberately intended for the object buffer to still available after disposing, but there's no guarantee reading from it as a stream will work (and writing will almost certainly fail).

答案 1 :(得分:1)

答案是。 任何实现IDisposable接口的对象都可以在using块中使用,以确保在using块结束时调用Dispose()。实际上,使用block充当try, finally块,而它们的最终块中有Dispose()

答案 2 :(得分:0)

可以返回流。您仍然可以在使用流的地方使用using语句:

using (var permitFileStream = CreatePermitFileMemoryStream(0))
{
     //Use your stream
}