Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failsafe disposal in an async world

Tags:

c#

idisposable

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?

like image 466
spender Avatar asked Feb 18 '11 00:02

spender


1 Answers

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.

like image 57
supercat Avatar answered Sep 19 '22 21:09

supercat