Is my C# static method in a non static class thread safe?

时间:2016-08-31 17:48:26

标签: c# multithreading

I have a C# class that can be instantiated with different constructors, but it also contains some static helper methods which only work with their parameters and can be called from other classes as well.

Now I wonder whether concurrent calls from different threads to such a method is thread safe or not, or in other words, is it possible that variables inside the static method get changed by call2, while call1 is still in process?

public class AwesomeClass
{
  /* constructors and stuff */

  public static bool HelperMethod(object o1)
  {
    string someString = "";
    Func<object, string> doSomething = (o) => { 

        string someOtherString == null;
        if (someString.Length == 0)
        {
          /* time consuming process using o... frequently
             changes someString and someOtherString */
        }
        return someOtherString;
    };
    return doSomething(o1).Length > 0 && someString.Length < 10;
  }
}

If someString in the example could be changed by a thread2 calling HelperMethod while doSomething is still working for thread1, I'd be in trouble.

3 个答案:

答案 0 :(得分:5)

If your static method does not change any member variables, and does not call mutating methods on its parameters, it is re-entrant, and is, therefore, thread-safe.

Static methods that perform mutating operations on their parameters may not be thread-safe when concurrent threads invoke the method with the same object as its parameter.

For example, if your method mutates o1 through methods, properties, or public variables, the method would no longer be thread-safe.

答案 1 :(得分:3)

HelperMethod is thread safe because it does not access any shared data. someString is local variable and it will be allocated again every time the method is called.

Note that this answer is not affected by the fact that someString is part of the closure. Separate closure object (which contains particular instance of someString) will be allocated on stack with every call to the HelperMethod.

答案 2 :(得分:0)

The variables someString and someOtherString are local to the call, they are not shared between calls. This is just as if had a function call itself, modifying variables in the 2nd call would not modify the first.

The one thing that could be unsafe is time consuming process using o..., If the operations you are doing to o1 are not safe to be done by multiple threads at once you could run into issues.