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

后端 未结 11 1498
不知归路
不知归路 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 13:47

    This would only be a race condition if it were modifying some variable external to the function. Your example is not doing that.

    That's basically what you're looking out for. Thread safe means that the function either:

    1. Does not modify external data, or
    2. Access to external data is properly synchronized so that only one function can access it at any one time.

    External data could be something held in storage (database/file), or something internal to the application (a variable, an instance of a class, etc): basically anything that is declared anywhere in the world that is outside of the function's scope.

    A trivial example of an un-thread safe version of your function would be this:

    private int myVar = 0;
    
    private void addOne(int someNumber)
    {
       myVar += someNumber;
    }
    

    If you call this from two different threads without synchronization, querying the value of myVar will be different depending on whether the query happens after all calls to addOne are complete, or the query happens in between the two calls, or the query happens before either of the calls.

提交回复
热议问题