c# – 带参数的静态方法是否安全?

前端之家收集整理的这篇文章主要介绍了c# – 带参数的静态方法是否安全?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上,我有一些类调用静态void提供out参数(在ASP网站中使用).

从我的理解,因为虚空有它自己的堆栈它是线程安全的,但是我不完全确定在使用输出时是否为真.有人可以澄清这个问题.谢谢!

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;

    }
}
}

解决方法

从MSDN文档:

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.

所以问题的答案取决于你如何调用静态方法.由于变量是通过引用传递的,如果你有多个线程调用你的方法并且它们传入相同的变量引用作为参数(即使这些参数是值类型,因为OUT导致通过引用显式传递),那么你的方法不是线程安全的.另一方面,如果多个线程调用您的方法,每个线程都传入自己的变量引用,那么您的方法将是线程安全的.

这不是特定于OUT或REF修饰符.修改引用类型数据的任何方法本身并不是线程安全的,您应该仔细考虑选择该路由的原因.通常,对于线程安全的方法,它应该是非常好的封装.

原文链接:https://www.f2er.com/csharp/99165.html

猜你在找的C#相关文章