[英]Are static methods with out arguments thread safe?
基本上,我有一些类调用静态void提供了参数(used in an ASP website)
。
从我的理解,因为虚空有它自己的堆栈它是线程安全的,但是我不完全确定在使用输出时是否为真。 有人可以澄清这个问题。 谢谢!
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;
}
}
}
你调用静态方法的方式,它不是线程安全的,因为它共享out引用。 但是如果从方法中返回一个值并且该方法中正在创建该变量,则它可以是线程安全的。
static int MyMethod(int input)
{
var output= 2;
...
return output;
}
从MSDN文档:
out关键字使参数通过引用传递。 这与ref关键字类似,不同之处在于ref要求在传递变量之前对其进行初始化。 要使用out参数,方法定义和调用方法都必须显式使用out关键字。
因此,您的问题的答案取决于您如何调用静态方法。 由于变量是通过引用传递的,如果你有多个线程调用你的方法并且它们传入相同的变量引用作为参数(即使这些参数是值类型,因为OUT导致通过引用显式传递),那么你的方法不是线程安全的。 另一方面,如果多个线程调用您的方法,每个线程都传入自己的变量引用,那么您的方法将是线程安全的。
这并不是特定于OUT或REF修饰符。 修改引用类型数据的任何方法本质上都不是线程安全的,您应该仔细考虑选择该路由的原因。 通常,对于线程安全的方法,它应该是非常好的封装。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.