<p>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.</p>

<p>Is this the proper way to use a mutex to prevent this from happening?</p>

<pre><code>lock (this.GetType()) {
    _log.Info("Doing Sync");
    DoSync();
    _log.Info("Sync Completed");
}
</code></pre>

[{'answer_id': 46928, 'author': 'Jonathan Webb', 'author_id': 1518, 'author_profile': 'https://Stackoverflow.com/users/1518', 'pm_score': 3, 'selected': False, 'text': '<p>TheSeeker is correct.</p>\n\n<p>Jeff Richter\'s advice in <a href="http://books.google.com/books?id=C-V_AAAACAAJ&amp;dq=clr+via+c%23&amp;ei=k6TBSPjYOomUzATIs8WIDg" rel="nofollow noreferrer">Clr Via C#</a> (p638-9) on locking is to create a private object specifically for the purpose of being locked.</p>\n\n<pre><code>private Object _lock = new Object();\n\n// usage\nlock( _lock )\n{\n    // thread-safe code here..\n}\n</code></pre>\n\n<p>This works because _lock cannot be locked by anything outside the current class.</p>\n\n<p>EDIT: this is applicable to threads executing within a single process. @David Mohundro\'s answer is correct for inter-process locking.</p>\n'}, {'answer_id': 46952, 'author': 'David Mohundro', 'author_id': 4570, 'author_profile': 'https://Stackoverflow.com/users/4570', 'pm_score': 5, 'selected': True, 'text': '<p>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 <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex" rel="nofollow noreferrer">System.Threading.Mutex</a> object.</p>\n\n<p>Here is a usage example:</p>\n\n<pre><code>bool createdNew;\nusing (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))\n{\n    try\n    {\n        mtx.WaitOne();\n\n        MessageBox.Show("Click OK to release the mutex.");\n    }\n    finally\n    {\n        mtx.ReleaseMutex();\n    }\n}\n</code></pre>\n\n<p>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.</p>\n'}]
['https://Stackoverflow.com/questions/46909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1512/']