ok, its a little more complicated than the question.
class A
{
static int needsToBeThreadSafe = 0;
public static void M1()
{
needsToBeThreadSa
To start with I agree with the answers using lock()
, that is the safest way.
But there exists a more minimalist approach, your sample code only shows single statements using needsToBeThreadSafe
and since int
is atomic you only need to prevent caching by the compiler using volatile:
class A
{
static volatile int needsToBeThreadSafe = 0;
}
But if you need needsToBeThreadSafe to be 'ThreadSafe' over multiple statements, use a lock.