Is the following object thread safe?
I’ll make one instance and use it using two or more threads, is this a good way to approach this?
public class ASyncBuffer<T>
{
readonly object _locker = new object();
private T _value;
private bool _dirty;
public T GetValue()
{
lock (_locker)
{
_dirty = false;
return _value;
}
}
public void SetValue(T value)
{
lock (_locker)
{
_dirty = true;
_value = value;
}
}
public bool Dirty
{
get
{
lock (_locker)
{
return _dirty;
}
}
}
}
The object itself is thread safe, but make sure you consider your usage of it as well. For example, if your usage looks like this:
That usage is NOT thread safe since the value of
Dirtycould change between when you check it and when you actually get the value.To avoid that issue (and make minimal use of locking), you would want to use it like so: