Is the “switch” statement evaluation thread-safe?

后端 未结 4 699
南方客
南方客 2021-02-05 04:04

Consider the following sample code:

class MyClass
{
    public long x;

    public void DoWork()
    {
        switch (x)
        {
            case 0xFF00000000         


        
4条回答
  •  自闭症患者
    2021-02-05 05:00

    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)
    {
        // ...
    }
    

提交回复
热议问题