我是新手,我在c#中有多线程实现。但是结果返回错误。 文件的编号为0到1000。但是返回值为1到1000。不是0。请帮助我理解问题。谢谢。
static void Number(int number)
{
List<string> l_number = new List<string>(File.ReadAllLines("number.txt"));
Console.WriteLine(l_number[number]);
}
static void Main(string[] args)
{
List<Thread> l_thread = new List<Thread>();
int soThread = 10;
Thread thread1 = new Thread(delegate ()
{
var numnum = 0;
while (true)
{
for (int i = 0; i < soThread; i++)
{
Thread threadnew = new Thread(delegate ()
{
//Console.WriteLine(numnum);
Number(numnum);
});
threadnew.Start();
l_thread.Add(threadnew);
numnum++;
Thread.Sleep(100);
}
foreach (Thread item in l_thread)
{
item.Join();
}
}
});
答案 0 :(得分:5)
您正在捕获 numnum
-它不是每个线程的,而计时意味着它不是被捕获时的值-它是在捕获时的值线程已计划的时间;尝试改为按作用域创建变量的副本,即
for (int i = 0; i < soThread; i++)
{
int copy = numnum;
Thread threadnew = new Thread(delegate ()
{
//Console.WriteLine(copy);
Number(copy);
});
// ...
}