且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

托管C ++中C#的lock()

更新时间:2023-02-08 13:39:05

等效于锁/SyncLock将使用

The equivelent to a lock / SyncLock would be to use the Monitor class.

在.NET 1-3.5sp中,lock(obj)可以:

In .NET 1-3.5sp, lock(obj) does:

Monitor.Enter(obj);
try
{
    // Do work
}
finally
{
    Monitor.Exit(obj);
}

从.NET 4开始,它将是:

As of .NET 4, it will be:

bool taken = false;
try
{
    Monitor.Enter(obj, ref taken);
    // Do work
}
finally
{
    if (taken)
    {
        Monitor.Exit(obj);
    }
}

您可以这样做:

System::Object^ obj = gcnew System::Object();
Monitor::Enter(obj);
try
{
    // Do work
}
finally
{
    Monitor::Exit(obj);
}