Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a thread-safe way to read/write a C# property in a class?

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)?

like image 379
n179911 Avatar asked Oct 14 '25 21:10

n179911


2 Answers

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.

like image 51
Jakub Lortz Avatar answered Oct 17 '25 11:10

Jakub Lortz


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;
            }
        }
    }
}
like image 39
Rustam Safin Avatar answered Oct 17 '25 11:10

Rustam Safin



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!