指数数组的边界之外试图启动多个线程 [英] Index was outside the bounds of the array while trying to start multiple threads

查看:140
本文介绍了指数数组的边界之外试图启动多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code,给了我一个索引数组的范围之外。我不知道为什么会这样,因为变量 I 应始终小于数组的长度喇嘛,因此不会导致此错误。

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!

推荐答案

瓶盖是你的问题就在这里。

Closures are your problem here.

基本上,而不是当您创建的lambda(中环)抓的价值,它抓住它时,它需要它。和电脑是如此之快,通过这种情况发生的时候,它已经跳出循环。和值的3。
下面是一个例子(不运行它尚未):

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();
    }
}

想想你所期望的结果是什么。难道是 012 你在想什么?

现在运行它。

其结果将是 333

下面是一些修改code,它会解决它:

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.

这篇关于指数数组的边界之外试图启动多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆