Search code examples
c#asp.netasynchronousstreamdispose

Dispose Stream While Still in Use by an Asynchronous Task


I have a fairly big stream (represents an image). I have two tasks to do:

  1. I want to upload the stream to the cloud using an async method (I assume the method is backed by Task.Run)
  2. While the stream is being uploaded, I need to locally read the stream (in order to create a thumbnail out of the image).

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.


Solution

  • 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.