c# – 在尝试启动多个线程时,Index超出了数组的范围
发布时间:2020-12-16 00:07:44 所属栏目:百科 来源:网络整理
导读:我有这个代码,它给了我一个“索引超出了数组的范围”.我不知道为什么会发生这种情况,因为变量i应该总是小于数组bla的长度,因此不会导致此错误. private void buttonDoSomething_Click(object sender,EventArgs e){ ListThread t = new ListThread(); string[
我有这个代码,它给了我一个“索引超出了数组的范围”.我不知道为什么会发生这种情况,因为变量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别无选择,只能在循环结束前接受它.这将为您提供预期的结果,也不例外. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |