I am developing some utilities to control threading for a game server and am experimenting with using an IDisposable “token” so that I can use code like this:
using(SyncToken playerListLock = Area.ReadPlayerList())
{
//some stuff with the player list here
}
The idea being that I acquire a read lock on the list of players in an area and it is automatically unlocked when it goes out of scope with the using block. So far this is all implemented and working, but I am worried about the timing of the call to Dispose().
Does the SyncLock variable simply get marked for disposal when the program leaves the using block and then get cleaned up by the Garbage Collector at some point later, or does the current thread execute the Dispose() method as a part of leaving the using block?
This pattern is basically RAII, where a lock is the resource being allocated. An example of this pattern (ie, using an IDisposable “token”) has also been used by Jon Skeet in his MiscUtils here
It’s cleaned up immediately after the
usingscope exits.In effect, this
is syntactic sugar for
The very purpose of
usingis to enable RAII-like functionality in C#, which doesn’t feature deterministic destruction.