How do I know if this C# method is thread safe?

后端 未结 11 1542
不知归路
不知归路 2020-12-07 13:19

I\'m working on creating a call back function for an ASP.NET cache item removal event.

The documentation says I should call a method on an object or calls I know wil

11条回答
  •  误落风尘
    2020-12-07 14:08

    In the above example no.

    Thread safety is mainly to do with stored state. You can make the above example non thread safe by doing this:

    static int myInt;
    
    static int addOne(int someNumber){
    myInt = someNumber;
    return myInt +1; 
    }
    

    This will mean that due to context switching thread 1 might get to the call myInt = someNumber and then context switch, lets say thread 1 just set it to 5. Then imagine that thread 2 comes in and uses 6 and returns 7. Then when thread 1 wakes up again it will have 6 in myInt instead of the 5 that it was using and return 7 instead of the expected 6. :O

提交回复
热议问题