Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 线程输入参数_C#_Multithreading_Visual Studio_Thread Safety - Fatal编程技术网

C# 线程输入参数

C# 线程输入参数,c#,multithreading,visual-studio,thread-safety,C#,Multithreading,Visual Studio,Thread Safety,我想在线程列表中运行一个具有不同值的类。像这样: int index = 0; foreach (TreeNode nd in tvew.Nodes[0].Nodes) { threadping[index] = new Thread(delegate() { this.Invoke(new DelegateClientState(InvokeCheckNetworkState), new object[] {nd}); });

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

     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++;
     }
但是当我调试代码时,我看到class参数只是最后一个值。 我的意思是,当我浏览thread类时,我看到每次该类运行时,输入参数的值都是最后一个线程的最后一个值


有人能告诉我为什么吗?

这是因为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}); });
如果我们使用编译器技术,这是因为编译器生成一个包含循环变量的匿名类,以便线程委托可以访问它。这是预期的行为,尽管当你第一次遇到它时可能有点违反直觉


有关闭包和变量捕获的详细说明,或。这通常被称为“访问修改的闭包”错误。如果您在StackOverflow或Google上搜索该术语,您将获得大量解释该术语的点击。

您能否显示初始化Threading集合的代码。什么是“类参数”或者您正在调试的线程类?tnx,它可以工作。另一个问题:为什么我的线程不能同时工作?我将断点指向第一个循环结束时引发的“InvokeCheckNetworkState”的第一行。就像线程等待前一个线程完成一样。我的意思是你不能同时工作。我该怎么办?