Don P Don P - 1 year ago 101
C# Question

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

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 == "")
/* time consuming process using o... frequently
changes someString and someOtherString */
return someOtherString;
return doSomething(o1).length > 0 and 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.

Answer Source

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.