C#-参数线程在静态方法中安全吗? [英] C# - Are Parameters Thread Safe in a Static Method?

查看:128
本文介绍了C#-参数线程在静态方法中安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法是线程安全的吗?好像不是...

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.

请注意,由ref 传递的参数不一定是线程安全的,因为这将潜在地允许单个变量在两个或多个线程之间共享,这将需要同步.

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.

此外,如果您将一个不可变的引用类型实例(即自定义类)作为参数传递,则该类的内部状态将需要同步,因为它可能被多个线程使用. 引用本身将是线程安全的,因为它作为副本传递(除非使用ref传递).

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

这篇关于C#-参数线程在静态方法中安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆