I am new to C#. In Java, I can make read/write of a Java class member by having 'synchronized' keyword in the setter/getter method.
Can you please tell me what is the right way to do the same in C#? In C# there is no synchronized keyword. Should I use '[MethodImpl(MethodImplOptions.Synchronized)] annotation' mentioned in C# version of java's synchronized keyword??
Or use Monitor.Enter (and subsequently Monitor.Exit)?
Use Monitor.Enter
/Exit
(or lock
- a syntactic sugar for Monitor
) with private object _lock = new object()
field.
Don't use MethodImplOptions.Synchronized
. It locks on this
, so it's possible that some other code will lock on the same instance causing deadlocks.
Locking on the instance or on the type, as with the Synchronized flag, is not recommended for public types, because code other than your own can take locks on public types and instances. This might cause deadlocks or other synchronization problems.
As Lortz said the best way is to use lock
public class ThreadSafeSetters
{
private bool _foo;
private object _locker = new object();
public bool Foo
{
get
{
lock (_locker)
{
return _foo;
}
}
set
{
lock (_locker)
{
_foo = value;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With