奇怪的索引越界异常?

时间:2019-04-18 11:09:10

标签: c# .net multithreading

我正在使用for循环通过以下代码启动线程:

internal static void ProcessAllDirectories(string baseLocationFirstLang, string baseLocationSecondLang)
    {
        string[] dirPathsFirst = Directory.GetDirectories(baseLocationFirstLang, "*", SearchOption.AllDirectories);
        string[] dirPathsSecond = Directory.GetDirectories(baseLocationSecondLang, "*", SearchOption.AllDirectories);
        Array.Sort(dirPathsFirst);
        Array.Sort(dirPathsSecond);
        CountdownEvent countDownLatch = new CountdownEvent(dirPathsFirst.Length);

        for (int i = 0; i < dirPathsFirst.Length; i++)
        {
            Thread perDirThread = new Thread(() =>
            {
                CommentAccumulator.AccumulateCommentsInDir(dirPathsFirst[i], dirPathsSecond[i]);
                countDownLatch.Signal();
            });
            perDirThread.Start();
        }

        countDownLatch.Wait();
    }

dirPathsFirst的长度为51。但是,我得到一个IndexOutOfBoundsException,因为i的值是51,但是根据循环的限制,它不应该这样。我认为由于多线程而正在发生某些事情。

0 个答案:

没有答案