gpt4 book ai didi

c# - 多线程 C# : Does not return the result as I expected

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:28 25 4
gpt4 key购买 nike

我是新手,我有一个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);
});

// ...
}

关于c# - 多线程 C# : Does not return the result as I expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55809936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com