Search code examples
c++-cliraii

Can RAII be implemented for .Net Monitor::Enter/Exit (in C++ CLI)


being forced :( to work in C++ CLI I'm looking for a way to do RAII locking. What I came up with is :

ref class RAIIMonitor
{
    RAIIMonitor();
    T^ t;
public:
    RAIIMonitor(T^ t_)
    {

        t=t_;
        System::Threading::Monitor::Enter(t_);
    }
    ~RAIIMonitor()
    {
        System::Threading::Monitor::Exit(t);
    }
    !RAIIMonitor()
    {
        assert(0); // you are using me wrong
    }
};

usage:

 //begining of some method in MyRefClass
 RAIIMonitor<MyRefClass> monitor(this);    

So is this correct way, if no is there a way to do it, if yes is there a way to do it better?


Solution

  • Microsoft provides a class to do this. #include <msclr/lock.h>, and have a look at the lock class. Combine that with stack semantics, and you get RAII locking.

    For the simple use case, simply declare the lock object as a local variable, and pass in the object to lock on. When the destructor is called via stack semantics, it releases the lock.

    void Foo::Bar()
    {
        msclr::lock lock(syncObj);
        // Use the protected resource
    }
    

    The lock class also provides Acquire, TryAcquire, and Release methods. There's a constructor that can be used to not perform the lock immediately, instead to lock later, and you call Acquire or TryAcquire yourself.

    (If you look at the implementation, you'll see that it's a full implementation of what you had started on with your RAIIMonitor class.)