Synchronize function

how can I do in C # that my function will be protected by a semaphore mutex aka sync a function in JAVA

+2


a source to share


4 answers


You don't want to sync functions like Java is a bad idea because they use a locking construct that might interfere with the other. You want to lock the object. Basically, in the class you want to protect, create a private member variable of an object of type

private readonly object lock_ = new object();

      



Then, in whatever method you need to synchronize, use the lock construct to automatically enter and leave the lock: -

public void SomeMethod()
{
    lock(lock_)
    {
         // ...... Do Stuff .........
    }
}

      

+4


a source


There is no good way to do this other than to do it yourself:



private readonly object _locker = new object();

public void MyMethod()
{
    lock (_locker) {
        // Do something
    }
}

      

+10


a source


+1


a source


As John said, you can use lock ()

, which is the same as Monitor.Enter and Monitor.Exit. If you need an interprocess mutex, use the Mutex class.

0


a source







All Articles