This documentation is archived and is not being maintained.

How to: Implement the lock C# Keyword in C++ 

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.


// CS_lock_in_CPP.cpp
// compile with: /clr /c
using namespace System::Threading;
ref class Lock {
   Object^ m_pObject;
   Lock % operator=( Lock const % );
   Lock( Lock const % );
   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

See Also