简体   繁体   中英

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 
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM