gpt4 book ai didi

c# - 线程输入参数

转载 作者:行者123 更新时间:2023-12-03 12:49:50 26 4
gpt4 key购买 nike

我想在线程列表中运行具有不同值的类。像这样 :

     int index = 0;
foreach (TreeNode nd in tvew.Nodes[0].Nodes)
{
threadping[index] = new Thread(delegate()
{ this.Invoke(new DelegateClientState(InvokeCheckNetworkState), new object[] {nd}); });

threadping[index].Name = nd.Name;
threadping[index].IsBackground = true;
threadping[index].Start();

index++;
}

但是当我调试代码时,我看到类参数只是最后一个值。
我的意思是当我通过线程类时,我看到每次该类运行时输入参数的值都是最后一个线程的最后一个值。

谁能告诉我为什么?

最佳答案

这是因为 nd 变量是在闭包中捕获的。当线程运行时,它们都引用同一个 TreeNode 实例,即最后一个分配给 nd 的实例。 .要修复,请使用在范围内不变的单独变量:

 foreach (TreeNode nd in tvew.Nodes[0].Nodes)
{
var current = nd;
threadping[index] = new Thread(delegate()
{ this.Invoke(new DelegateClientState(InvokeCheckNetworkState), new object[] {current}); });

如果我们了解编译器技术,则会发生这种情况,因为编译器会生成一个包含您的循环变量的匿名类,以便线程委托(delegate)可以访问它。这是预期的行为,尽管当您第一次遇到它时可能有点违反直觉。

关于闭包和变量捕获的详细解释, see the Captured Variables section here (bottom section) in a Jon Skeet article , 或 this article from Eric Lippert .这通常被称为“访问修改后的闭包”错误。如果你在 StackOverflow 或谷歌上搜索这个词,你会得到很多解释它的点击。

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

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