项目场景:c#中使用for循环多开线程后,在线程中再调用for循环使用的循环数量会报错超出索引限度
string[] strlist=new string[2] { "1", "2" };
for (int i = 0; i < strlist.Length; i++)
{
Task.Factory.StartNew(() =>
{
Console.WriteLine(strlist[i]);
});
}
``
# 解决方案:
(1)声明一个变量idexs变量将i赋值进去
```csharp
string[] strlist=new string[2] { "1", "2" };
for (int i = 0; i < strlist.Length; i++)
{
int index = i;
Task.Factory.StartNew(() =>
{
Console.WriteLine(strlist[index]);
});
}
(2)使用foreach循环
string[] strlist=new string[2] { "1", "2" };
foreach (var str in strlist)
{
Task.Factory.StartNew(() =>
{
Console.WriteLine(str);
});
}