gpt4 book ai didi

c# - 将列表传递给线程

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:59 24 4
gpt4 key购买 nike

我有一个接受List<int>的方法DoWork。我有一个巨大的List<int> Ids。我将庞大的 list 分为4个子 list :

List<List<int>> t = (List<List<int>>)SplitColumn<int>(Ids);

( SplitColumn从对 splitting a list into sub lists的回答中略作修改)。

我暂停了程序,并用调试器检查了 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();
}

最佳答案

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

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

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

要解决这个问题:
    for(int i = 0; i < t.Count; i++) 
{
int copy = i;
threads.Add(new Thread(() => DoWork(t[copy])));
}

关于c# - 将列表传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12866512/

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