views:

140

answers:

4

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
There actually is a mutex object; is it a bad idea?
Robert Harvey
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
+2  A: 

Maybe this tutorial from msdn will solve your problem :)

npinti
Please don't post old links. I edited to update to the current version.
John Saunders
That was the first hit on a google search...
npinti
@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
I did not even know you could strip out the parentheses.
Scott Chamberlain
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
Apologies then, I did not know that.
npinti
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
I thought that's what _I_ said.
John Saunders
...And an underscore *after* the variable name. There's a convention I haven't seen before.
Robert Harvey
This is the paraphrase version :)
Nelson
It won't compile either; no data type on the member variable.
Jesse C. Slicer
you are right! tanks!
@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
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