Using "use" with stream utilities in C # - when is Dispose called?

I’m developing some stream management utilities for a game server and experimenting with a token IDisposable"so I can use this code:

using(SyncToken playerListLock = Area.ReadPlayerList())
{
    //some stuff with the player list here
}

The idea is that I get a read lock on the list of players in the area, and it automatically unlocks when it leaves the scope using the block. So far, all this has been implemented and works, but I'm worried about the timing of the call Dispose().

Is the variable SyncLockfor deletion changed when the program leaves the usage block and then is cleared by the garbage collector at some point later, or does the current thread execute the method Dispose()as part of leaving the block using?

This pattern is basically RAII, where a lock is a dedicated resource. An example of this template (i.e., using the token IDisposable") was also used by John Skeet in his MiscUtils here

+3
source share
8 answers

It is cleaned immediately after the completion of the area using.

In essence, this

using(SyncToken playerListLock = Area.ReadPlayerList())
{
    //some stuff with the player list here
}

- syntactic sugar for

IDisposable playerListLock;
try {
    playerListLock = Area.ReadPlayerList();
}
finally {
    if (playerListLock != null) playerListLock.Dispose();
}

The goal itself usingis to include functionality like RAII in C #, which does not have deterministic destruction.

+11
source

Disposecalled when leaving an area using. Syntactic sugar for:

MyObj instance = null;
try
{
  instance = new MyObj();
}
finally
{
  instance.Dispose();
}
+3
source

Dispose() , using.
using # RAII ++.

+2

using docs , :

using , Dispose , . , try, finally; , , using .

, , , .

+1

Dispose , Dispose SyncToken, SyncLock , Dispose Pattern.

+1

, Dispose() , SyncToken GC, .

+1

using - try-finally:

using (var myObject = new MyObject())
{
    ...
}

:

MyObject myObject = null;

try
{
    myObject = new MyObject();
    ...
}
finally
{
    if (myObject != null)
    {
         myObject.Dispose();
    }
}

, , Dipose() using.

- GC . , .

+1

Dispose , , - .

, , : IDisposable

0

All Articles