Consider the following sample code:
class MyClass
{
public long x;
public void DoWork()
{
switch (x)
{
case 0xFF00000000
As you already assumed, the switch statement is not thread-safe and might fail in certain scenarios.
Furthermore, using lock
on your instance variable won't work neither, because the lock
statement expects an object
causing your instance variable to be boxed. Every time the instance variable is boxed, a new boxed variable will be created, making the lock
effectively useless.
In my opinion you have several options solving this issue.
lock
on a private instance variable of any reference type (object
will do the job)ReaderWriterLockSlim
to let multiple threads read the instance variable but only one thread write the instance variable at a time.Interlocked.Read
or Interlocked.Exchange
) and perform the switch
on the local variable. Note that this way you might use the old value for the switch
. You have to decide if this can cause problems in your concrete use-case.