Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronize function

how can i do in C# that my function will be guarded by mutex semaphore a.k.a synchronize function in JAVA

like image 864
aharon Avatar asked Mar 22 '26 04:03

aharon


2 Answers

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
    }
}
like image 59
John Saunders Avatar answered Mar 24 '26 18:03

John Saunders


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 .........
    }
}
like image 40
Stewart Avatar answered Mar 24 '26 18:03

Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!