在C#中使用'using'和线程实用程序 - 何时调用Dispose?

Sub*_*ied 3 c# multithreading semaphore idisposable

我正在开发一些实用程序来控制游戏服务器的线程,并正在尝试使用IDisposable"令牌",以便我可以使用这样的代码:

using(SyncToken playerListLock = Area.ReadPlayerList())
{
    //some stuff with the player list here
}
Run Code Online (Sandbox Code Playgroud)

我的想法是,我在一个区域中的玩家列表上获得了一个读锁定,当它超出使用块的范围时,它会自动解锁.到目前为止,这一切都已实施并正在运行,但我担心电话会议的时间安排Dispose().

SyncLock当程序离开使用块然后稍后由垃圾收集器清理时,变量是否被简单地标记为处理,或者当前线程是否Dispose()作为离开using块的一部分执行该方法?

这种模式基本上是RAII,其中锁是被分配的资源.(即,使用这种模式的一个例子IDisposable"令牌")也已经在他的MiscUtils使用乔恩斯基特这里

Jon*_*Jon 11

using示波器退出后立即清理它.

实际上,这个

using(SyncToken playerListLock = Area.ReadPlayerList())
{
    //some stuff with the player list here
}
Run Code Online (Sandbox Code Playgroud)

是语法糖

IDisposable playerListLock;
try {
    playerListLock = Area.ReadPlayerList();
}
finally {
    if (playerListLock != null) playerListLock.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

其目的using是在C#中启用类似RAII的功能,它不具有确定性破坏功能.