Udostępnij za pośrednictwem


How to: Implement the lock C# Keyword (C++/CLI)

This topic shows how to implement the C# lock keyword in Visual C++. For more information, see lock Statement (C# Reference).

You can also use the lock class in the C++ Support Library. See Synchronization (lock Class) for more information.

Example

// CS_lock_in_CPP.cpp
// compile with: /clr
using namespace System::Threading;
ref class Lock {
   Object^ m_pObject;
public:
   Lock( Object ^ pObject ) : m_pObject( pObject ) {
      Monitor::Enter( m_pObject );
   }
   ~Lock() {
      Monitor::Exit( m_pObject );
   }
};

ref struct LockHelper {
   void DoSomething();
};

void LockHelper::DoSomething() {
   // Note: Reference type with stack allocation semantics to provide 
   // deterministic finalization

   Lock lock( this );   
   // LockHelper instance is locked
}

int main()
{
   LockHelper lockHelper;
   lockHelper.DoSomething();
   return 0;
}

See Also

Other Resources

Interoperability with Other .NET Languages (C++/CLI)