Are static methods without arguments thread safe?

Basically, I have several classes that cause a static void that provides arguments (used in an ASP website) .

From my understanding, because void has its own stack, it is thread safe, however I'm not quite sure if this is true when outs are used. Can someone clarify the problem. Thanks!

 namespace ThreadTest { class Program { static void Main(string[] args) { int helloWorldint = 0; bool helloWorldbool = false; int helloWorldintOut = 0; bool helloWorldboolOut = false; setHelloWorlds(helloWorldint, helloWorldbool, out helloWorldintOut, out helloWorldboolOut); Console.WriteLine(helloWorldintOut); Console.WriteLine(helloWorldboolOut); } public static void setHelloWorlds(int helloWorldint, bool helloWorldbool, out int helloWorldintOut, out bool helloWorldboolOut) { helloWorldintOut = helloWorldint + 1; helloWorldboolOut = true; } } } 
+7
source share
2 answers

From the MSDN documentation:

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires the variable to be initialized before it is passed. To use the out parameter, both the method definition and the invocation method must explicitly use the out keyword.

So the answer to your question depends on how you call your static method. Since a variable is passed by reference, if you have several threads calling your method And they pass the same variable references as parameters (even if these parameters are types of values, since OUT causes transmission by reference explication), your method is not thread safe . On the other hand, if several threads call your method, each of which passes its references to variables, then your method will be thread safe.

This does not apply to OUT or REF modifiers. Any method that modifies data in a reference type is essentially not thread safe, and you should carefully consider why you choose this route. Generally, for a method to be thread safe, it must be very encapsulated.

+2
source share

As you invoke the static method, it will not be thread safe as it separates the links. But if you return a value from your method and this variable is created in the method, it may be thread safe.

 static int MyMethod(int input) { var output= 2; ... return output; } 
+3
source share

All Articles