I have class Foo
that stores a string
. The Bar
property is expected to be accessed/assigned to by multiple threads and reads must access the latest value so I put a lock
in place:
public class Foo
{
private readonly object _lock = new object();
private string _bar;
public string Bar
{
get
{
lock (_lock)
{
return _bar;
}
}
set
{
lock (_lock)
{
_bar = value;
}
}
}
}
I am wondering will using Interlocked.Exchange
will achieve the same result but potentially better performance?
public class Foo
{
private string _bar;
public string Bar
{
get => _bar;
set => Interlocked.Exchange(ref _bar, value);
}
}