how can i do in C# that my function will be guarded by mutex semaphore a.k.a synchronize function in JAVA
+6
A:
There's no good way to do this, except to do it yourself:
private readonly object _locker = new object();
public void MyMethod()
{
lock (_locker) {
// Do something
}
}
John Saunders
2010-05-12 19:41:38
There actually is a mutex object; is it a bad idea?
Robert Harvey
2010-05-12 19:46:10
Mutex is slower than lock (Monitor object). It's really only meant for cross-process communication and I believe uses the OS built-in mutex functionality.
Nelson
2010-05-12 19:48:00
Please don't post old links. I edited to update to the current version.
John Saunders
2010-05-12 19:43:42
@npinti: who posted the link? You, or Google? When posting MSDN links, always use the link that has no version number in parentheses.
John Saunders
2010-05-12 19:51:30
When MSDN creates an article that is expected to persist (with changes) over several releases, they create a single URL. To indicate the different versions of the same article, they add the version in parentheses. A link without the parentheses will always be for the latest release of .NET. A link with parentheses will always be for the specific version of .NET.
John Saunders
2010-05-12 20:34:27
A:
You don't want synchronize functions like Java - they're a bad idea because they use a lock construct which other can interfere with. What you want is a lock object. Basically, in the class you want to protect, create a private member variable of type object
private readonly object lock_ = new object();
Then in any method you need to synchronize, use the lock construct to enter and leave the lock automatically:-
public void SomeMethod()
{
lock(lock_)
{
// ...... Do Stuff .........
}
}
Stewart
2010-05-12 19:43:14
...And an underscore *after* the variable name. There's a convention I haven't seen before.
Robert Harvey
2010-05-12 19:45:27
@John Saunders - I think we submitted around the same time - if you want the glory let me know how to pass it on.@Robert Harvey - I'm pretty sure I got the underscore after the variable name convention for member variables from reviewing Accelerated C++ by Koenig and Moo. I kind of liked it and started using it in my own code. When we abandoned hungarian it kind of stuck on my team. I like it better than m_ for sure, and underscore before is not legal C++ and I like to use the same conventions everywhere.
Stewart
2010-05-12 20:34:46
A:
As John said, you can use lock ()
, which is the same thing as Monitor.Enter and Monitor.Exit. If you need a cross-process mutex, use the Mutex class.
Nelson
2010-05-12 19:44:40