我是新手,我有一个c#的多线程实现。但结果返回错误。文件 <number.txt>
有数字 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();
}
}
});
您正在捕获 numnum
- 它不是每个线程,时间意味着它不是捕获时的值 - 它是线程得到调度时的值;尝试为每个范围创建一个变量副本,即
for (int i = 0; i < soThread; i++)
{
int copy = numnum;
Thread threadnew = new Thread(delegate ()
{
//Console.WriteLine(copy);
Number(copy);
});
// ...
}
我是一名优秀的程序员,十分优秀!