c# – 在尝试启动多个线程时,Index超出了数组的范围

我有这个代码,它给了我一个“索引超出了数组的范围”.我不知道为什么会发生这种情况,因为变量i应该总是小于数组bla的长度,因此不会导致此错误.

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

有人能告诉我如何解决这个问题,为什么会发生这种情况.谢谢!

解决方法

关闭是你的问题.

基本上,不是在创建lambda(在循环中)时抓取值,而是在需要时抓取它.计算机速度如此之快,以至于发生这种情况时,它已经脱离了循环.价值为3.
这是一个例子(不要运行它):

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

想想你期望结果如何.你想到的是它吗?

现在运行它.

结果将是333.

这是一些修改过的代码

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

现在它会正常工作.这次循环结束时,该值超出了范围,因此lambda别无选择,只能在循环结束前接受它.这将为您提供预期的结果,也不例外.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...