0

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#?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
user1947862
  • 13
  • 1
  • 3

1 Answers1

0

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();
}
Zereges
  • 5,139
  • 1
  • 25
  • 49
  • You shouldn't use `Mutex` in the normal case as it's more heavyweight than `Monitor` or the `lock` statement on an arbitrary lock object. See for example here: http://stackoverflow.com/questions/1164038/monitor-vs-mutex-in-c-sharp – Matthias247 Jan 30 '17 at 11:55
  • Hi ..In C sharp , mutext.Dispose is required ? does Realease mutex realease and disposes the thread? – user1947862 Apr 05 '17 at 08:58