传递 "out paramater" 时传递给被调用方法的值是什么
what is the value that is passing into the called method when "out paramater" is passed
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);
}
当我们传递参数时,被调用方法接收到的值应该是多少?? "whether it is zero or the value we are passing"
基于您的代码
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()
执行之前完成,那么 thread1()
将收到 21
。但是,如果执行没有完成,则接收 10
作为输入。
如果您从 thread2()
函数中删除此行 Thread.Sleep(5000);
,则以上内容为真。
但是如果你不这样做,在理想情况下 10 将同时传递给函数和主线程 print 10 ,但这也取决于上下文切换......你的输出在这里不固定。这一切都在处理和执行上。
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);
}
当我们传递参数时,被调用方法接收到的值应该是多少?? "whether it is zero or the value we are passing"
基于您的代码
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()
执行之前完成,那么 thread1()
将收到 21
。但是,如果执行没有完成,则接收 10
作为输入。
如果您从 thread2()
函数中删除此行 Thread.Sleep(5000);
,则以上内容为真。
但是如果你不这样做,在理想情况下 10 将同时传递给函数和主线程 print 10 ,但这也取决于上下文切换......你的输出在这里不固定。这一切都在处理和执行上。