Adam
Adam

Reputation: 488

C# - Are Parameters Thread Safe in a Static Method?

Is this method thread-safe? It seems as though it isn't...

public static void Foo(string _str, Guid _id)
{
    _str = _str + _id.ToString();

    /*
        Do Stuff 
    */

    return 
}

Upvotes: 10

Views: 5933

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564333

The parameters are, in this case, two immutable values. Within a method, only a single thread is operating on the set of parameters, as multiple threads calling the method will each have their own stack and execution context, which means each thread has their own independent set of parameters and local variables, so no other thread can impact those variables.

As such, this is completely thread safe in relation to those two variables.

Note that, parameters passed by ref are not necessarily thread safe, as that would potentially allow a single variable to be shared among two or more threads, which would require synchronization.

Also, if you pass a reference type instance that isn't immutable (ie: a custom class) as a parameter, the internal state of that class would need synchronization, as it could potentially be used by more than one thread. The reference itself would be thread safe, as it's passed as a copy (unless passed using ref).

Upvotes: 23

Henk Holterman
Henk Holterman

Reputation: 273169

The parameters themselves are by definition thread-safe. It does not matter whether the method is static or not.

They could however be references to other data and that is not automatically thread-safe.

Your example uses a value type and an immutable reference types so this particular case is OK.

Upvotes: 5

Related Questions