可以为 .Net Monitor::Enter/Exit 实现 RAII(在 C++ CLI 中)

NoS*_*tAl 3 c++-cli raii

被迫 :( 在 C++ CLI 中工作我正在寻找一种方法来进行 RAII 锁定。我想出的是:

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
    }
};
Run Code Online (Sandbox Code Playgroud)

用法:

 //begining of some method in MyRefClass
 RAIIMonitor<MyRefClass> monitor(this);    
Run Code Online (Sandbox Code Playgroud)

那么这是正确的方法,如果没有,有没有办法做到这一点,如果是,有没有办法做得更好?

Dav*_*Yaw 5

Microsoft 提供了一个类来执行此操作。#include <msclr/lock.h>,看看锁类。将其与堆栈语义相结合,您将获得 RAII 锁定。

对于简单的用例,只需将锁​​定对象声明为局部变量,并传入要锁定的对象。当通过堆栈语义调用析构函数时,它会释放锁。

void Foo::Bar()
{
    msclr::lock lock(syncObj);
    // Use the protected resource
}
Run Code Online (Sandbox Code Playgroud)

锁类还提供AcquireTryAcquireRelease方法。有一个构造函数可用于不立即执行锁定,而是稍后锁定,您自己调用 Acquire 或 TryAcquire。

(如果您查看实现,您会发现它是您从 RAIIMonitor 类开始的内容的完整实现。)