Consider the following sample code:
class MyClass
{
public long x;
public void DoWork()
{
switch (x)
{
case 0xFF00000000
Yes, the switch
statement itself, as shown in your question, is thread-safe. The value of field x
is loaded once into a (hidden) local variable and that local is used for the switch
block.
What isn't safe is the initial load of the field x
into a local variable. 64-bit reads aren't guaranteed to be atomic, so you could be getting stale and/or torn reads at that point. This could easily be resolved by using Interlocked.Read, or similar, to explicitly read the field value into the local in a thread-safe way:
long y = Interlocked.Read(ref x);
switch (y)
{
// ...
}