Is the “switch” statement evaluation thread-safe?

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

    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.

    1. Use lock on a private instance variable of any reference type (object will do the job)
    2. Use ReaderWriterLockSlim to let multiple threads read the instance variable but only one thread write the instance variable at a time.
    3. Atomically store the value of the instance variable to a local variable in your method (e.g. using 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.

提交回复
热议问题