'C# and thread-safety of a bool
I am very confused about this subject - whether reading/toggling a bool value is thread-safe.
// case one, nothing
private bool v1;
public bool V1 { get { return v1; } set { v1 = value; } }
// case two, with Interlocked on set
private int v2;
public int V2 { get { return v2; } set { Interlocked.Exchange(ref v2, value); } }
// case three, with lock on set
private object fieldLock = new object();
private bool v3;
public bool V3 { get { return v3; } set { lock (fieldLock) v3 = value; } }
Are all of them thread-safe?
EDIT
From what I have read (click) atomicity of bool does not guarantee it will be thread safe. Will then volatile type help?
Solution 1:[1]
A little bit late but should be useful to the others.
You can implement your own thread safe boolean in the following way:
// default is false, set 1 for true.
private int _threadSafeBoolBackValue = 0;
public bool ThreadSafeBool
{
get { return (Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 1, 1) == 1); }
set
{
if (value) Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 1, 0);
else Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 0, 1);
}
}
Be sure to use Property everywhere, never access int variable directly.
Solution 2:[2]
Nope, it isn't. But the solution is quite easy. To make a bool (or anything, actually) thread safe, it's easy to use lock statement like this:
object locker = new object();
protected bool _somebool;
public bool Somebool
{
get
{
lock (locker)
return _somebool;
}
set
{
lock (locker)
_somebool = value;
}
}
Now you may enjoy your thread safe of <T>.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lilo0 |
| Solution 2 | Theodor Zoulias |
