Index was outside the bounds of the array while trying to start multiple threads

那年仲夏 提交于 2019-12-22 10:34:01

问题


I have this code which gives me an "Index was outside the bounds of the array". I don't know why is this happening because variable i should always be less than the length of array bla and therefore not cause this error.

private void buttonDoSomething_Click(object sender, EventArgs e)
{
    List<Thread> t = new List<Thread>();

    string[] bla = textBoxBla.Lines;

    for (int i = 0; i < bla.Length; i++)
    {
        t.Add(new Thread (() => some_thread_funmction(bla[i])));
        t[i].Start();
    }
}

Could someone tell me how to fix this and why is this happening. Thanks!


回答1:


Closures are your problem here.

Basically, instead of grabbing the value when you create the lambda (in the loop), it grabs it when it needs it. And computers are so fast that by the time that happens, it's already out of the loop. And the value's 3. Here's an example (don't run it yet):

private void buttonDoSomething_Click(object sender, EventArgs e)
{
    List<Thread> t = new List<Thread>();
    for (int i = 0; i < 3; i++)
    {
        t.Add(new Thread (() => Console.Write(i)));
        t[i].Start();
    }
}

Think about what you'd expect the result to be. Would it be 012 you're thinking?

Now run it.

The result will be 333.

Here's some modified code that'll fix it:

private void buttonDoSomething_Click(object sender, EventArgs e)
{
    List<Thread> t = new List<Thread>();
    string[] bla = textBoxBla.Lines;
    for (int i = 0; i < bla.Length; i++)
    {
        int y = i; 
        //note the line above, that's where I make the int that the lambda has to grab
        t.Add(new Thread (() => some_thread_funmction(bla[y]))); 
        //note that I don't use i there, I use y.
        t[i].Start();
    }
}

Now it'll work fine. This time the value goes out of scope when the loop finishes, so the lambda has no choice but to take it before the loop finishes. That will get you your expected result, and no exception.




回答2:


What you are seeing is a race condition. Your for loop is completing prior to the threads actually starting. So by the time the threads actually start the value of i is outside of the bounds of the array.

Try copying the index value and pass in the copy instead.

private void buttonDoSomething_Click(object sender, EventArgs e)
{
    List<Thread> t = new List<Thread>();

    string[] bla = textBoxBla.Lines;

    for (int i = 0; i < bla.Length; i++)
    {
        int index = i;
        t.Add(new Thread (() => some_thread_funmction(bla[index])));
        t[i].Start();
    }
}


来源:https://stackoverflow.com/questions/16843510/index-was-outside-the-bounds-of-the-array-while-trying-to-start-multiple-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!