Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-like thread synchronization in C#

I am a Java programmer and I know a few things about threading int Java.

In Java I can lock a method by using synchronized keyword:

private int a;
private int b;
private int c;
private synchronized void changeVars()
{
  a = 4;
  b = 2;
  c = a+b;
}

I searched in msdn and saw that there are a few toys in c# to play with threads. Such as monitor.Enter, monitor.Exit, lock or an advanced one mutex.

But what I need is to synchronize one method. What is the equivalent of it in c#?

Thanks in advance.

like image 661
JCasso Avatar asked Dec 19 '25 02:12

JCasso


1 Answers

There's no direct equivalent in C#, but you can do the same thing with this:

private readonly object changeVarsLockObject = new object();

private void changeVars()
{
  lock(changeVarsLockObject)
  {
    a = 4;
    b = 2;
    c = a+b;
  }
}
like image 75
FacticiusVir Avatar answered Dec 20 '25 17:12

FacticiusVir



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!