A common pattern in C++ is to create a class that wraps a lock – the lock is either implicitly taken when object is created, or taken explicitly afterwards. When object goes out of scope, dtor automatically releases the lock. Is it possible to do this in C#? As far as I understand there are no guarantees on when dtor in C# will run after object goes out of scope.
Clarification: Any lock in general, spinlock, ReaderWriterLock, whatever. Calling Dispose myself defeats the purpose of the pattern – to have the lock released as soon as we exit scope – no matter if we called return in the middle, threw exception or whatnot. Also, as far as I understand using will still only queue object for GC, not destroy it immediately…
Your understanding regarding
usingis incorrect, this is a way to have scoped actions happen in a deterministic fashion (no queuing to the GC takes place).C# supplies the
lockkeyword which provides an exclusive lock and if you want to have different types (e.g. Read/Write) you’ll have to use theusingstatement.P.S. This thread may interest you.