Would returning a Lazy<Stream> from a method be a good idea for deferring the cost of opening a FileStream? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question 开发者_如何学运维I have a scenario where I want to clearly convey that it's the caller's responsibility for disposing a stream while at the same time preventing the caller from discovering the underlying file's path -- the caller shouldn't know that the stream came from the file system. Also, the caller isn't going to need the stream until later on, so I probably don't need to open it immediately.
Given that, I thought that it might be a good idea to leverage Lazy<T> for this purpose, as in:
public Lazy<Stream> GetContent(string key)
{
string path = GetFilePath(key);
return new Lazy(() => File.OpenRead(path));
}
Am I over-thinking this? Should I just return a Stream instead?
Be aware that returning Lazy<T>
in this way means that if multiple pieces of code re-use the same lazy "factory" then they will get exactly the same stream. For example, if one piece of code disposes the stream then the others will be attempting to use the same disposed stream etc.
If you really need to defer creation of the stream then I'd suggest returning a Func<T>
instead. This will allow the returned delegate to be safely shared and re-used, creating a new stream instance each time it is invoked.
My own preference would probably be to just return a plain Stream
, and document very clearly that it's the caller's responsibility to handle the disposal.
Lazy<> is the exact opposite, it is a creation detail, not a destruction detail. Furthermore, the client has no decent reason to delay construction when interested in the content. These are just wrong signals, return a Stream.
the caller shouldn't know that the stream came from the file system
Caller may cast GetContent(key).Value
to FileStream
. You may want to decorate it with something if the need is not to expose FileStream
.
Anyway personally I don't see any advantages of using Lazy here.
精彩评论