这段代码导致IndexOutOfBoundsException
谁能告诉我为什么?
我不明白为什么会导致IndexOutOfBoundsException
private static String TRACE_PATH = "..\\..\\TRACES";
static void Main(string[] args)
{
if (Directory.Exists(TRACE_PATH))
{
String[] traceEntries = Directory.GetFiles(TRACE_PATH);
Thread[] traceReaders = new Thread[traceEntries.Length];
for (int i = 0; i < traceEntries.Length; i++)
{
traceReaders[i] = new Thread(()=>readTrace(traceEntries[i]));
traceReaders[i].Start();
}
}
Console.Read();
}
private static void readTrace(String traceFile)
{
using (StreamReader sr = new StreamReader(traceFile))
{
//code to use the trace file...
}
}
最佳答案
只需在循环内声明一个临时变量即可。您正在捕获变量而不是值。
for (int i = 0; i < traceEntries.Length; i++)
{
var j = i;
traceReaders[j] = new Thread(()=>readTrace(traceEntries[j]));
traceReaders[j].Start();
}
关于c# - 导致IndexOutOfBounds异常的线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20927401/