C # - Are there Thread Safe parameters in a static method?

Is this method thread safe? It seems that this is not ...

public static void Foo(string _str, Guid _id) { _str = _str + _id.ToString(); /* Do Stuff */ return } 
+4
source share
2 answers

In this case, the parameters are two constant values. Within a method, only one thread works on a set of parameters, since each thread calling the method will have its own stack and execution context, which means that each thread has its own independent set of parameters and local variables, so no other thread may affect these variables.

Thus, it is completely thread safe with respect to these two variables.

Please note that parameters passed with ref are not necessarily thread safe, as this potentially allows you to use one variable for two or more threads, which will require synchronization.

In addition, if you pass an instance of a reference type that is not immutable (that is: a custom class) as a parameter, the internal state of this class will need synchronization, since it can potentially be used by more than one thread. This link itself would be thread safe, as it was transmitted as a copy (if not passed using ref ).

+15
source

The parameters themselves are, by definition, thread safe. It doesn't matter if the method is static or not.

However, they may be links to other data and are not automatically thread safe.

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

+5
source

Source: https://habr.com/ru/post/1487548/


All Articles