user6445891
user6445891

Reputation: 101

Are static methods with out arguments thread safe?

Basically, I have a few classes that call a static void that provides out arguments (used in an ASP website).

From my understand because the void has it's own stack it's threadsafe, however I'm not entirely sure if thats true when outs are used. Can someone clarify the issue. 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;

    }
}
}

Upvotes: 9

Views: 2685

Answers (2)

akardon
akardon

Reputation: 46056

The way you are calling the static method, it wouldn't be thread safe, as it shares the out references. But if you return a value from your method and that variable is being created in the method, it could be thread safe.

static int MyMethod(int input)
{
    var output= 2;
    ...
    return output;
}

Upvotes: 3

DVK
DVK

Reputation: 2792

From the MSDN documentation:

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

So the answer to your question depends on how you are calling your static method. Since the variable is passed by reference, if you have multiple threads calling your method AND they are passing in the same variable references as parameters (even if those parameters are value types since OUT causes passing by reference explicity) then your method is not threadsafe. On the other hand, if multiple threads call your method, each passing in its own variable references, then your method would be threadsafe.

This isn't really specific to the OUT or REF modifiers. Any method that modifies data on a reference type is not inherently thread-safe, and you should carefully consider why you are choosing to go that route. Typically, for a method to be threadsafe, it should be very well-encapsulated.

Upvotes: 9

Related Questions