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

问题描述:

托管C ++是否等效于C#的 lock()和VB的SyncLock?如果可以,该如何使用?

Does managed C++ have an equivalent to C#'s lock() and VB's SyncLock? If so, how do I use it?

等效于锁/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);
}