In the synchronous world, C# makes the management of all things disposable really rather easy:
using(IDisposable someDisposable=bla.bla())
{
//do our bidding
}
//don't worry too much about it
However, when we go async, we no longer have the convenience of the using
block. One of the best strategies I've encountered is the CCR iterator which allows us to use async code "as if it were synchronous". This means we can keep our using
block in the iterator handler and not get too bogged down in the complex decision of when to dispose and catching all the cases where disposal is required.
However, in many cases, invoking CCR can seem like overkill, and to be honest, although I'm quite comfortable with CCR, to the uninitiated it can look like double-dutch.
So my question is: what other strategies exist for the management of one's IDisposable's, when the disposable objects must persist beyond the immediate scope?
One approach is to have all methods that would not be able to coexist with the disposal method take a lock while they run, and check a queue for objects needing disposal when they finish. The disposal method could then add itself to the queue, use TryEnter to try to acquire the lock, dispose the object and delete it from the queue if successful, or else let the current holder of the lock handle the disposal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With