0

Usually I use a memory stream with the well known using pattern.

using(var mem = new MemoryStream(blob))
{
  foo(mem);
}

No imagine a function bar(Func<Stream>) defined in a client library that I have to use. I could call it like this

bar(() => new MemoryStream(blob));

but then nobody is disposing the stream properly. How to work around it? Should Func be used with IDisposable types at all?

aggsol
  • 2,343
  • 1
  • 32
  • 49
  • Why not putting the first section of code into the Func? Just add brackets in the func body – auX Aug 08 '19 at 11:25
  • @Aggsol What is the main purpose for this `FUNC`? Why return a stream object at all? If you need an array of bytes or a file or something to that affect you can always pass that back from your `FUNC` auX if the OP adds a using statement inside of the function, the stream will be disposed upon the call to return. – Ryan Wilson Aug 08 '19 at 11:29
  • As i remember, you can call `.Dispose()` method by hand – nonForgivingJesus Aug 08 '19 at 11:31
  • @RyanWilson I dunno it is a client library I have to use. – aggsol Aug 08 '19 at 11:32
  • 2
    Usually, the creator of an `IDisposable` is the owner, so the one who creates an object is responsible for disposing of it. So, the `bar` method should dispose it. However, it's unclear whether the `Func` will create an object or will just provide an existing instance. In that case, the class that provides the `Func` should dispose of the object. – dymanoid Aug 08 '19 at 11:32

1 Answers1

2

It seems like a poorly designed library.

If you know for a fact that the library does not dispose of the stream and it doesn't hold the Func<Stream> for later use, then you can do this:

using(var mem = new MemoryStream(blob))
{
    bar(() => mem);
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172