谁应该负责关闭流 [英] Who should be responsible for closing a stream
问题描述
我写了创建目录的文件的应用程序,它可以归结与其他元数据文件,如附件和缩略图。
我试图抽象接口目录的地步,消费者目录并不需要了解用于存储文件的基础文件系统。所以,我创建了一个名为接口 IFileSystemAdaptor
这是如下图所示。
public接口IFileSystemAdaptor:IDisposable接口
{
无效WriteFileData(字符串文件名,流数据);
流ReadFileData(字符串文件名);
无效DeleteFileData(字符串文件名);
无效ClearAllData();
无效WriteMetaFileData(字符串文件名,路径字符串,流数据);
流ReadMetaFileData(字符串文件名,字符串路径);
无效DeleteMetaFileData(字符串文件名,字符串路径);
无效ClearMetaFilesData(字符串文件名);
}
基本上我IFileSystemAdaptor接口公开文件的平面列表,这也可以与其他元数据文件相关联。
正如你可以看到我使用引用泛型流
反对抽象的接口连接到文件的数据。这样一个实施目录的可以从硬盘返回的文件,而另一个可从web服务器返回数据。
现在我试图找出如何让我的程序离开流开放。有没有一个拇指什么成员应该关闭流的规则?应的流的消费者将其关闭,或应该原始创建的流的构件负责关闭它
我的规则:
如果一个流的消费者将其关闭
-
如果我从一个方法返回一个流,对消费者负责。我把它给你,这是你的responsilibity。
-
如果我接受一个流作为方法的参数,我不关闭它。在退出方式,我不知道调用方法仍然需要它。这是你的流,我只是借用它,我不想惹你。
-
如果我创建了一个流,并将其传递给另一个方法,我的方法将其关闭(或尝试)时,我与它正在做的。我不知道你会如何处理它,但它是我流的,所以我负责吧。
I'm writing an application that creates a "Catalog" of files, which can be attributed with other meta data files such as attachments and thumbnails.
I'm trying to abstract the interface to a catalog to the point where a consumer of a catalog does not need to know about the underlying file system used to store the files. So I've created an interface called IFileSystemAdaptor
which is shown below.
public interface IFileSystemAdaptor:IDisposable
{
void WriteFileData(string fileName, Stream data);
Stream ReadFileData(string filename);
void DeleteFileData(string filename);
void ClearAllData();
void WriteMetaFileData(string filename, string path, Stream data);
Stream ReadMetaFileData(string filename, string path);
void DeleteMetaFileData(string filename, string path);
void ClearMetaFilesData(string filename);
}
Essentially my IFileSystemAdaptor interface exposes a flat list of files, that can also be associated with additional meta data files.
As you can see I'm using references to generic Stream
objects to abstract the interface to a file's data. This way one implementation of a Catalog could return files from a hard disk, while another could return the data from a web server.
Now I'm trying to figure out how to keep my program from leaving streams open. Is there a rule of thumb for what members should close streams? Should the consumer of a stream close it, or should the member that original created the stream be responsible for closing it.
My Rules:
Should the consumer of a stream close it
If I return a stream from a method, the consumer is responsible. I'm giving it to you, It's your responsilibity.
If I accept a stream as a parameter in a method, I don't close it. When exiting the method, I don't know if the calling method still needs it. It's your stream, I'm just borrowing it, and I don't want to mess you up.
If I create a stream and pass it to another method, my method closes it (or tries to) when I am done with it. I don't know what you are going to do with it, but it's my stream, so I am responsible for it.
这篇关于谁应该负责关闭流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!