基本上,我有一些类调用静态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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
从 MSDN 文档:
out 关键字导致参数通过引用传递。这类似于 ref 关键字,不同之处在于 ref 要求在传递变量之前对其进行初始化。要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字。
所以你的问题的答案取决于你如何调用你的静态方法。由于变量是通过引用传递的,如果您有多个线程调用您的方法并且它们将相同的变量引用作为参数传递(即使这些参数是值类型,因为 OUT 导致显式通过引用传递),那么您的方法不是线程安全的。另一方面,如果多个线程调用您的方法,每个线程都传入自己的变量引用,那么您的方法将是线程安全的。
这并不是真正特定于 OUT 或 REF 修饰符。任何修改引用类型数据的方法本质上都不是线程安全的,您应该仔细考虑为什么选择这条路线。通常,对于线程安全的方法,它应该被很好地封装。
| 归档时间: |
|
| 查看次数: |
1116 次 |
| 最近记录: |