using – It’s not just for memory management

When we designed the using statement waaaay back in the first version of C#, we decided to call it using because we thought it had other purposes outside of the usual use:

using (StreamWriter writer = File.CreateText(”blah.txt”))
{ … }

Today I was responding to a customer suggestion, in which he suggested language support for the ReaderWriterLock class, so it could be more like the built-in lock statement. Unfortunately, ReaderWriterLock.AcquireReader() doesn’t return something that’s IDisposable, but it’s pretty easy to add that with a wrapper class.

I spent about 15 minutes writing a wrapper, then I had a thought, did a google search, and came across this article, which already has it done. Plus, the version in the article probably wraps the whole class, and has likely been tested.

Comments (16)

  1. Mark Mullin says:

    A floor wax _and_ a dessert topping ?! Incredible.

    I’ve also found using to be helpful for things you really really would like released ‘deterministically’, i.e. limited, expensive resources – I implemented a wrapper class for Websphere MQ (customer choice, not mine) and implemented IDisposable for the MQReader and MQWriter classes so that the resources would get freed up as soon as the logic was done with them – handy – but I’d never thought of managing state like the article you linked…..

  2. Yes, deterministic destruction is very useful. Coming from a C++ background I *love* how .net makes tons of things easier but real destructors is the one thing I miss the most (well, that and templates but I just got my VS 2005 beta DVD so I’m not allowed to complain about that anymore :)).

    Anyway thanks for the pointer!

  3. Darren Oakey says:

    speaking of such things, has any1 found any way at all to determine, in the disposer, whether or not you are being disposed because of an exception or not? We’ve basically used using as a poor man’s anonymous method -eg:

    > using (Transaction.Named("Save the thing"))

    > {

    > …

    > }

    and similar, because we want the behaviour to always be the same, so don’t want people to create their own try/catch blocks… however since we can’t workout whether it’s an exception or not (I tried searching the stackframe and everything! 🙁 ) we ACTUALLY have to write:

    > using (Transaction.Named("Save the thing"))

    > {

    > …

    > Transaction.Commit(); // geez would I like to remove this

    > }

    any1 succeeded in doing that?

  4. Samuel Jack says:


    Have a look at this link:

    It might give you some ideas about a different approach.

  5. John Rusk says:

    >speaking of such things, has any1 found any way at all to determine, in the disposer, whether or not you are being disposed because of an exception or not?

    That would be cool. Like you, I had a look at it and gave up. Something like Delphi’s ExceptObject would be the idea – a function that you can call in your Dispose method that returns "the current exception", or null if there isn’t one.

    Eric, is this fundamentally impossible, because of the way the MSIL draws a distinction between catch blocks and finally blocks?

    I’m hoping to sort out an alternative with anonymous methods once I start using Whidbey.

  6. Darren Oakey says:

    Samuel –

    that approach is exactly identical to mine (except I’m using a much cleaner syntax :)) – and they both have the same disadvantage – you have to have that last line (for me ransaction.Commit, for system.transactions: ts.Consistent = true ) – they are doing exactly the same thing.

    My point is, that last line SHOULDN’T be necessary! If we could determine _in any way_ that an exception has occurred, it wouldn’t be.

    I tried doing things like replacing the default thread error handler, but that didn’t give me exactly what I wanted because it only gets called wayyy too late.. I’ve tried searching the stack – putting markers in and all sorts of things – but there seems to be no easy way to do it. Basically, we are in a "Finally" block, and need to determine whether it was triggered by an exception or not. In the new version of whidbey, we would be able to do it, because we can get events on exceptions – but then we have anonymous methods, so can do the whole thing in a much better way.

    My problem is – I’m using (and have been for months) the above syntax right NOW in tons of production code – and I would desperately like a way of not requiring the Transaction.Commit – because people can and do forget to put it in.

    I searched for ages, and ran across some people who hinted it could be done, but it was some weird com interop thing – and I wasn’t sure it was actually relevant. All I want is "I’m in a finally block (|dispose of using variable) – is there currently an exception being handled?" – If I get that, "using" suddenly becomes 100x more powerful, because it provides a generic way of encapsulating a try catch finally block, and the processing involved.

  7. Eric says:


    I don’t know enough about the exception handling internals to know for sure, but I don’t think that we have the exception context around in the finally block.

  8. Mark Mullin says:

    I just found another interesting use for using 🙂

    I developed a reference management class that allows for certain types of object references to transit between strong and weak reference states – the idea being that when I’m not actively using the object, if it has to go away I can make another one, but that if it stays around, that’s cool too.

    The reference manager object holds a pair of references, a strong reference (not always present) and a weak reference. I implemented IDisposable for this so that it nulled out the strong reference, and then started using it in using statement in the form

    using(SomeObject obj = (SomeObject) refMgr.StrongReference())


    < do things>


    The strong reference method will use the weak ref if it’s valid, or create it and return the target if not – on exit from the using scope, the strong reference pointer is cleared by IDisposable.

    This pattern seems to work well, cuts down on the job of managing weak/strong references

    whatcha think ?

  9. Mark Mullin says:

    uhh – typo

    that should be

    using (StrongReference sr = refMgr.StrongReference())

  10. What I always wanted for using/IDisposable is the counterpart method to Dispose. E.g. Acquire or whatever. So that I can write

    using (resource)



    and on entering using clause it would call Acquire and on exit it would call Release, both are methods of (some) IUsable interface.

  11. Krishna says:


    You are not alone in the request, we also have a same kind of of the demos from the PDC was managing transactions through attributes to class / methods from System.Transactions namespace..similar to AutoCommit from EnterpriseServicess..these probably would be part of Indigo..