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

后端 未结 11 1541
不知归路
不知归路 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:03

    That addOne function is indeed thread safe because it doesn't access any data that could be accessed by another thread. Local variables cannot be shared among threads because each thread gets its own stack. You do have to make sure, however, that the function parameters are value types and not reference types.

    static void MyFunction(int x) { ... } // thread safe. The int is copied onto the local stack.
    
    static void MyFunction(Object o) { ... } // Not thread safe. Since o is a reference type, it might be shared among multiple threads. 
    

提交回复
热议问题