ok, its a little more complicated than the question.
class A
{
static int needsToBeThreadSafe = 0;
public static void M1()
{
needsToBeThreadSafe = RandomNumber();
}
public static void M2()
{
print(needsToBeThreadSafe);
}
}
now i require that between M1() and M2() calls 'needsToBeThreadSafe' stays Thread Safe.
You have two choices: the easiest given your presented code is the
volatile
keyword. declareneedsToBeThreadSafe
asstatic volatile int
and that will guarantee that any thread that references that variable will get the "latest" copy, and the variable won't be cached within your code.That being said, if you want to more generally ensure that
M1()
andM2()
execute "atomically" (or at least exclusively of each other), then you want to use alock
. The cleanest syntax is with a "lock block", like this:As to which approach to take, that's up to you and should be determined by the code. If all you need is to ensure that a member assignment gets propagated to all threads and isn't cached, then the
volatile
keyword is simpler and will do the job just fine. If it's beyond that, you may want to go with thelock
.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 sinceint
is atomic you only need to prevent caching by the compiler using volatile:But if you need needsToBeThreadSafe to be 'ThreadSafe' over multiple statements, use a lock.
How About:
Sound like you need a Volatile member.
What you might be trying to ask about is the [ThreadStatic] attribute. If you want each thread that uses the class
A
to have its own separate value ofneedsToBeThreadSafe
then you just need to decorate that field with the [ThreadStatic] attribute.For more info refer to the MSDN documentation for
ThreadStaticAttribute
.