【问题标题】:I don't know why it's throwing System.ArgumentOutOfRangeException [duplicate]我不知道为什么会抛出 System.ArgumentOutOfRangeException [重复]
【发布时间】:2020-01-15 05:22:57
【问题描述】:

我试图弄清楚为什么会显示此错误,但我不能。我认为一切都很好,但在某些时候 readTest 的值“i”是 == 2。这不应该...... listW 有 2 个对象,而“i”应该只有 0 和 1。我没有t 2 来自哪里。我做错什么了吗?我已经做了一些测试,而 i=2 只发生在 readTest 上。发生了什么事?

感谢大家的关注

public void readTest(int i)
        {
            for (int j = 0; j != leftListList[i].getKeyValues().Length; j++)
            {
                string read = ws.Read(listW[i], wi[i].GetKey(), leftListList[i].getKeyValues()[j]);
                WsRead wsRead = wi[i].BuildRead(read, leftListList[i].getKeyValues()[j]);
                readList.Add(wsRead);

                Console.WriteLine("READ: " + leftListList[i].getKeyValues()[j]);
            }
        }

        public void threadTest()
        {
            for (int i = 0; i != listW.Length; i++)
            {
                    Thread t = new Thread(() => readTest(i));
                    t.Start();
                }
            }

【问题讨论】:

  • 你有一个狂野的else 到处乱跑。
  • 查看foreach 循环,它们会使您的代码更具可读性。

标签: c# multithreading


【解决方案1】:

引入一个本地变量,比如index:

for (int i = 0; i < listW.Length; i++) // i < listW.Length is more readable
{
    int index = i;
    ...
    else 
    {
        // now each thread has its own index
        Thread t = new Thread(() => readTest(index));
        t.Start();
    }
}

当Thread终于开始(创建一个新线程需要时间),循环完成,因此i == 2

【讨论】:

  • 天哪!太感谢了!你是我的救星!
猜你喜欢
  • 1970-01-01
  • 2015-11-09
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多