Reputation: 3895
I have an object,
public class ExpensiveObject(HttpContext context, ....)
{
public Stream OnlyCareAboutThisStream { get; private set; }
}
I want to hold a reference to OnlyCareAboutThisStream, but don't care about the ExpensiveObject, which really is expensive.
What options do I have? Do I need to copy the stream? To elaborate, I'm going to queue this object (OnlyCareAboutThisStream) onto a Queue that will be written to disk slowly in a background thread.
Upvotes: 1
Views: 173
Reputation: 13335
No, you don't need to copy the stream. Simply hold a reference to the Stream from somewhere else and allow the ExpensiveObject to go out of scope.
You may want to implement IDisposable on your ExpensiveObject and explicitly dispose of it (although this is mutually exclusive WRT the ExpensiveObject going out of scope):
public class ExpensiveObject(HttpContext context, ....) : IDisposable
{
public Stream OnlyCareAboutThisStream { get; private set; }
}
...
Stream myStream = null;
using (var exObj = new ExpensiveObject(context))
{
myStream = exObj.OnlyCareAboutThisStream;
}
Upvotes: 0
Reputation: 1502486
It's not entirely clear what you're asking, but if you're considering code like this:
ExpensiveObject expensive = new ExpensiveObject(context);
Stream stream = expensive.OnlyCareAboutThisStream;
then the expensive object will be eligible for garbage collection after the second line, assuming it's not using some custom stream which has a reference to its "parent" expensive object.
Upvotes: 3