c# - 如何在C#中将参数传递给线程

标签 c# multithreading

全部 我搜索了这个问题,找到了很多答案,不难找到我的问题的解决方案。 但是,我有奇怪的经历,我不知道这就是为什么我要求人们给我一些建议的原因。 这是我的代码:

    void SetThread()
    {
        for (int i = 0; i < _intArrayLength; i++)
        {
            Console.Write(string.Format("SetThread->i: {0}\r\n", i));
            _th[i] = new Thread(new ThreadStart(() => RunThread(i)));
            _th[i].Start();
        }
    }

    void RunThread(int num)
    {
        Console.Write(string.Format("RunThread->num: {0}\r\n", num));
    }

是的,都是普通的线程代码。 我希望所有线程数组都应该调用 RunThread 方法 10 次。 应该是这样的

SetThread->i: 0
SetThread->i: 1
SetThread->i: 2
SetThread->i: 3
SetThread->i: 4
SetThread->i: 5
SetThread->i: 6
SetThread->i: 7
SetThread->i: 8
SetThread->i: 9
RunThread->num: 0
RunThread->num: 1
RunThread->num: 2
RunThread->num: 3
RunThread->num: 4
RunThread->num: 5
RunThread->num: 6
RunThread->num: 7
RunThread->num: 8
RunThread->num: 9

这就是我所期待的。顺序并不重要。 但我得到如下结果。

SetThread->i: 0
SetThread->i: 1
SetThread->i: 2
The thread '<No Name>' (0x18e4) has exited with code 0 (0x0).
The thread '<No Name>' (0x11ac) has exited with code 0 (0x0).
The thread '<No Name>' (0x1190) has exited with code 0 (0x0).
The thread '<No Name>' (0x1708) has exited with code 0 (0x0).
The thread '<No Name>' (0xc94) has exited with code 0 (0x0).
The thread '<No Name>' (0xdac) has exited with code 0 (0x0).
The thread '<No Name>' (0x12d8) has exited with code 0 (0x0).
The thread '<No Name>' (0x1574) has exited with code 0 (0x0).
The thread '<No Name>' (0x1138) has exited with code 0 (0x0).
The thread '<No Name>' (0xef0) has exited with code 0 (0x0).
SetThread->i: 3
RunThread->num: 3
RunThread->num: 3
RunThread->num: 3
SetThread->i: 4
RunThread->num: 4
SetThread->i: 5
SetThread->i: 6
RunThread->num: 6
RunThread->num: 6
SetThread->i: 7
RunThread->num: 7
SetThread->i: 8
RunThread->num: 8
SetThread->i: 9
RunThread->num: 9
RunThread->num: 10

我期望的是 RunThread 函数应该携带从 0 到 9 的参数 (num)。 而且我无法弄清楚该错误消息是什么。 “线程''~~等等。 谁能给我一些线索?

最佳答案

你是creating a closure over the loop variable - 一个简单的解决方法是只创建一个本地副本,这样您的线程就可以使用所需的值:

void SetThread()
    {
        for (int i = 0; i < _intArrayLength; i++)
        {
           int currentValue = i;
            Console.Write(string.Format("SetThread->i: {0}\r\n", i));
            _th[i] = new Thread(() => RunThread(currentValue));
            _th[i].Start();
        }
    }

关于c# - 如何在C#中将参数传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18177931/

相关文章:

c# - 当我尝试使用 .Include() 进行预加载时,EF Core 是延迟加载

c# - Winforms:从另一个类更新表单上的标签

java - 对单个线程的多个同时访问

c# - 如何使用 iTextsharp 在服务器映射路径上保存 pdf

c# - 在将数据从 Excel 文件转换为 XML 时,点被隐式转换为散列

c# - 使用绑定(bind)而不是循环检查/取消选中所有复选框?

c# - 主人对他们的奴隶真正了解多少?

c - 读写器访问多个读者

python - 如何在Python中从另一个线程下拉出套接字?

c - 当使用free()时,内存使用不会减少