Is the “switch” statement evaluation thread-safe?

后端 未结 4 531
南方客
南方客 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:07

    C#'s switch statement isn't evaluated as a series of if conditions (as VB's can be). C# effectively builds up a hashtable of labels to jump to based on the value of the object and jumps straight to the correct label, rather than iterating through each condition in turn and evaluating it.

    This is why a C# switch statement doesn't deteriorate in terms of speed as you increase the number of cases. And it's also why C# is more restrictive with what you can compare to in the switch cases than VB, in which you can do ranges of values, for example.

    Therefore you don't have the potential race condition that you've stated, where a comparison is made, the value changes, the second comparison is made, etc, because there is only one check performed. As for whether it's totally threadsafe - I wouldn't assume so.

    Have a dig with reflector looking through a C# switch statement in IL and you'll see what's happening. Compare it to a switch statement from VB which includes ranges in the values and you'll see a difference.

    It's been quite a few years since I looked at it, so things may have changed slightly...

    See more detail about switch statement behaviour here: Is there any significant difference between using if/else and switch-case in C#?

提交回复
热议问题