Who should be responsible for closing a stream

前端 未结 3 1272
后悔当初
后悔当初 2021-02-14 13:38

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 ab

相关标签:
3条回答
  • 2021-02-14 13:45

    My Rules:

    Should the consumer of a stream close it

    1. If I return a stream from a method, the consumer is responsible. I'm giving it to you, It's your responsilibity.

    2. 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.

    3. 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.

    0 讨论(0)
  • 2021-02-14 13:47

    My spontaneous thought in this case is that the consumer should hold the responsibility for closing the streams. An IFileSystemAdaptor can't know when the consumer is done using the stream, so it also can't decide when to close it.

    0 讨论(0)
  • 2021-02-14 13:48

    In effect the last object to use the stream should be responsible for closing it, and that is generally the caller.

    Enjoy!

    0 讨论(0)
提交回复
热议问题