I have a fairly big stream
(represents an image). I have two tasks to do:
Task.Run
)My question is: Since the same stream object is referenced by two pointers in two different asynchronous tasks, where should I dispose the stream? Can I detect the number of pointers referencing a stream? or at least can I detect whether the stream is being in use (even by another thread) before disposing it?
I don't know which of the two tasks finishes first.
Provided your implementation is thread safe and you really need to use a disposable from multiple places you can use RefCountDisposable from ReactiveExtensions (Rx). Eg:
RefCountDisposable refDisposable = new RefCountDisposable(stream);
IDisposable ref1 = refDisposable.GetDisposable();
IDisposable ref2 = refDisposable.GetDisposable();
When both ref1
and ref2
are disposed stream
will be disposed.