Is this the proper use of a mutex?

Question :

Is this the proper use of a mutex?,

Answer :

I have a situation where I might have multiple instances of a program running at once, and it’s important that just one specific function not be executing in more than one of these instances at once.

Is this the proper way to use a mutex to prevent this from happening?

lock (this.GetType()) {      _log.Info("Doing Sync");      DoSync();      _log.Info("Sync Completed");  }  


You said multiple instances of one application, so we’re talking about two program.exe’s running, right? The lock statement won’t lock across multiple programs, just within the program. If you want a true Mutex, look at the object.

Read More  Best implementation for Key Value Pair Data Structure?

Here is a usage example:

bool createdNew;  using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))  {      try      {          mtx.WaitOne();            MessageBox.Show("Click OK to release the mutex.");      }      finally      {          mtx.ReleaseMutex();      }  }  

The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.

Read More  How to obtain good concurrent read performance from disk

That’s the answer Is this the proper use of a mutex?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you