代码之家  ›  专栏  ›  技术社区  ›  Jagadeesh Bevara

当传递“out paramater”时,传递给被调用方法的值是什么

  •  -5
  • Jagadeesh Bevara  · 技术社区  · 7 年前
    static void Main(string[] args)
    {
        int i = 10;
    
        Program th = new Program();
    
        Thread t2 = new Thread(() => thread2(out i));
        t2.Start();
        Thread t1 = new Thread(() => thread1(i));
        t1.Start();
        Thread.Sleep(5000);
    
        Console.WriteLine("Main thread exits." + i);
        Console.ReadLine();
    }
    
    static void thread1(int i)
    {
        Console.WriteLine(i);
        i = 100;
    }
    
    static void thread2(out int i) // what should be the value of i???
    {
        Thread.Sleep(5000);
        i = 21;           
        Console.WriteLine(i);
    }
    

    当我们传递参数时,在被调用的方法中接收到的值应该是多少??“无论是零还是我们传递的值”

    1 回复  |  直到 7 年前
        1
  •  0
  •   Pranay Rana    7 年前

    基于您的代码

    static void Main(string[] args)
    {
        int i = 10;
    
        Program th = new Program();
    
        Thread t2 = new Thread(() => thread2(out i));
        t2.Start();
        Thread t1 = new Thread(() => thread1(i));
        t1.Start();
        Thread.Sleep(5000);
    
        Console.WriteLine("Main thread exits." + i);
        Console.ReadLine();
    }
    

    第一个函数thread2将接收值 i = 10 . 但是

    在第二个函数中,您将接收 i =10 or i =21 ,因为它完全取决于在CLR/CPU级别执行。

    我想说的是如果你 thread2() 方法执行在到达执行之前完成 thread1() 然后 螺纹1() 将收到 21 . 但如果执行未完成,则接收 10 作为输入。

    如果你记住这一行,以上是正确的 Thread.Sleep(5000); 从您的 螺纹2() 作用

    但如果您不这样做,那么在理想情况下,10将同时传递给函数和主线程print 10,但这也取决于上下文切换。。。此处未固定输出。这一切都取决于处理和执行。