将列表传递给线程

use*_*753 1 c# multithreading .net-4.0

我有一个接受List<int>被叫的方法DoWork.我有一个巨大的 List<int> Ids.我将巨大的列表分成4个子列表:

List<List<int>> t = (List<List<int>>)SplitColumn<int>(Ids);
Run Code Online (Sandbox Code Playgroud)

(SplitColumn稍微修改了将列表拆分为子列表的答案).

我暂停了程序并t使用调试器进行了检查,它是按照我的预期完全划分的四个列表.

然后,我正在尝试做的是生成四个线程(每个子列表一个).我遇到麻烦的部分是通过四个列表.我遇到了问题,我不确定这里发生了什么:

        List<Thread> threads = new List<Thread>();

        for(int i = 0; i < t.Count; i++) 
        {
            threads.Add(new Thread(() => DoWork(t[i])));
        }

        foreach (Thread thread in threads)
        {
            thread.Start();
        }


        foreach (Thread thread in threads)
        {
            thread.Join();
        }
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 8

这是一个经典的,称为捕获循环变量.

在此代码中,i所有线程共享相同的变量.当线程运行时,主线程将进行i == t.Count,因此范围异常.

    for(int i = 0; i < t.Count; i++) 
    {
        threads.Add(new Thread(() => DoWork(t[i])));
    }
Run Code Online (Sandbox Code Playgroud)

要解决这个问题:

    for(int i = 0; i < t.Count; i++) 
    {
        int copy = i;
        threads.Add(new Thread(() => DoWork(t[copy])));
    }
Run Code Online (Sandbox Code Playgroud)