gpt4 book ai didi

c# - 线程和函数参数

转载 作者:行者123 更新时间:2023-11-30 20:02:53 27 4
gpt4 key购买 nike

以下代码在没有多线程的情况下也能正常工作。但是如果我使用线程,它就会失败。如果我在 checkedListBox 中选择了多个项目,第一个将被忽略,其他的是随机的...

我认为提交数据有问题。你怎么看?

    private void sendCom(String com)
{
//send command to selected item
int i=0;
String IP;
foreach (var item in checkedListBox1.CheckedItems)
{
Console.WriteLine(item.ToString());
IP = item.ToString();
theThreads[i] = new Thread(new ThreadStart(() => sendComThread(IP, com) ));
theThreads[i].Start();
//sendCom(IP, com);
i++;
}
}

private void sendComThread(String IP, String com)
{
// send an command
System.Console.WriteLine(IP + com);
}

最佳答案

根本问题是您的变量捕获是捕获单个变量,然后在所有线程之间共享。因此,每次线程读取共享变量时,它都会获取最近刚好放入其中的任何值。除了语义错误之外,共享变量上还存在明显的数据竞争。

最简单的解决方案是为每个线程创建一个变量。只需将变量的声明 移到循环内即可。像这样:

foreach (var item in checkedListBox1.CheckedItems)
{
....
String IP = item.ToString(); //NB variable declared inside loop
theThreads[i] = new Thread(new ThreadStart(() => sendComThread(IP, com) ));
....
}

现在每个线程都有自己的字符串变量的私有(private)实例。

关于c# - 线程和函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16048433/

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