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?

5
  • Why not putting the first section of code into the Func? Just add brackets in the func body Commented Aug 8, 2019 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. Commented Aug 8, 2019 at 11:29
  • As i remember, you can call .Dispose() method by hand Commented Aug 8, 2019 at 11:31
  • @RyanWilson I dunno it is a client library I have to use. Commented Aug 8, 2019 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<Stream> will create an object or will just provide an existing instance. In that case, the class that provides the Func<Stream> should dispose of the object. Commented Aug 8, 2019 at 11:32

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.