我试图产生一定数量的线程。但是当我将参数传递给函数时,输出是随机的。它多次选择变量“i”的一些值并忽略一些。我是 C# 的新手。如果我做错了什么,请解释。
using System;
using System.Threading;
public class first
{
public static void tone(int i)
{
Console.WriteLine("Hi ! this is thread : {0} ",i);
Thread.Sleep(10);
}
public static void Main(String[] args)
{
int i;
for (i = 0; i < 10; i++)
{
Thread th1 = new Thread(()=>tone(i) );
th1.Start();
// Console.WriteLine(i);
}
Console.WriteLine("hey there!");
Console.ReadLine();
}
最佳答案
因为closure :
将您的代码更改为:
int i;
for (i = 0; i < 10; i++)
{
int j = i;
Thread th1 = new Thread(()=>tone(j) );
th1.Start();
// Console.WriteLine(i);
}
关于c# - 为什么生成线程时会出现意外输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23735861/