本文介绍了导致IndexOutOfBounds异常的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码导致IndexOutOfBoundsException谁能告诉我为什么?我不明白为什么会导致IndexOutOfBoundsException

This piece of code causes an IndexOutOfBoundsExceptionCan anyone please tell me why?I can't undertstand why it is causing an 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...
    }
}

推荐答案

只需在循环内声明一个临时变量.您正在捕获变量而不是值.

Just declare a temp variable inside your loop. You are capturing the variable not the value.

 for (int i = 0; i < traceEntries.Length; i++)
 {
       var j = i;   
       traceReaders[j] = new Thread(()=>readTrace(traceEntries[j]));
       traceReaders[j].Start();
 }

这篇关于导致IndexOutOfBounds异常的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 14:06