user1947862 user1947862 - 2 years ago 276
C# Question

C++ Mutex replacement in C sharp

I have a project which is written in C++ which has functionality of file copy and folder creations. It uses the

Mutex.Lock()
and
Mutex.unLock()
methods in C++.

I need to replicate the same in C#.

Please suggest which is the best way to write the C++ methods
mutext.Lock()
and
Mutex.unlock()
in C#?

Answer Source

C++ has no Mutex class. It has std::mutex, which provides .lock() and .unlock().

So, in C++ you have,

std::mutex mtx;

void thr_fnc(){
    mtx.lock();
    // CS
    mtx.unlock();
}

To achieve same functionality in C#, you can do

Mutex mtx = new Mutex();

void thr_fnc(){
    mtx.WaitOne();
    // CS
    mtx.ReleaseMutex();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download