Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
}
like image 255
Adam Avatar asked Jun 21 '13 19:06

Adam


2 Answers

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).

like image 106
Reed Copsey Avatar answered Sep 24 '22 06:09

Reed Copsey


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.

like image 5
Henk Holterman Avatar answered Sep 23 '22 06:09

Henk Holterman