n179911
n179911

Reputation: 20291

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

Upvotes: 4

Views: 4033

Answers (3)

Mingo.Link
Mingo.Link

Reputation: 168

In some scenarios, volatile might be sufficient (although it depends what you are guarding against and what the data-type is):

private volatile int _counter;
public int Counter
{
    get { return _counter; }
    set { _counter = value; }            
}

OR lock it

#region public int Counter { set; get; }
private int _counter;
private object sync_counter = new object();
public int Counter
{
    set
    {
        lock(sync_counter)
        {
            _counter = value;
        }
    }
    get
    {
        lock(sync_counter)
        {
            return _counter;
        }
    }
}
#endregion

Upvotes: 4

Rustam Safin
Rustam Safin

Reputation: 842

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;
            }
        }
    }
}

Upvotes: 4

Jakub Lortz
Jakub Lortz

Reputation: 14896

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.

Upvotes: 4

Related Questions