Thread-safe use of a singleton's members
Posted
by Anthony Mastrean
on Stack Overflow
See other posts from Stack Overflow
or by Anthony Mastrean
Published on 2008-09-03T20:29:15Z
Indexed on
2010/06/08
21:32 UTC
Read the original article
Hit count: 203
I have a C# singleton class that multiple classes use. Is access through Instance
to the Toggle()
method thread-safe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it?
public class MyClass
{
private static readonly MyClass instance = new MyClass();
public static MyClass Instance
{
get { return instance; }
}
private int value = 0;
public int Toggle()
{
if(value == 0)
{
value = 1;
}
else if(value == 1)
{
value = 0;
}
return value;
}
}
© Stack Overflow or respective owner