0

I'm getting an index out of bounds exception in a toy project I made to follow a tutorial. The loop is supposed to start a bunch of tasks and store the Task objects in an array. After the for loop finishes I await the tasks using Task.WhenAll() and print the result. The loop is supposed to terminate when i < Pages.Length == false, but the out of bounds error is being thrown when i == Pages.Length (after the loop should have terminated).

My main question is: Why is the variable i being allowed to reach Pages.Length?

This seems to be an extremely common loop, so any insight into this would be greatly appreciated.

(The loop in question is the topmost loop on line 6)

        private async void AsyncClick(object sender, RoutedEventArgs e)
        {
            Stopwatch watch = Stopwatch.StartNew();
            Task<WebPageData>[] tasks = new Task<WebPageData>[Pages.Length];
            ConsoleOutput = $"Starting Download {Environment.NewLine}";
            for (int i = 0; i < Pages.Length; i++)
            {
                tasks[i] = Task.Run(() => DownloadPage(Pages[i]));
            }

            WebPageData[] results = await Task.WhenAll(tasks);

            for (int i = 0; i < tasks.Length; i++)
            {
                ConsoleOutput += $"{results[i].URL} : The length is {results[i].PageContents.Length}{Environment.NewLine}";
            }

            watch.Stop();
            ConsoleOutput += $"Finished downloading in time: {watch.ElapsedMilliseconds} ms";
        }


        private WebPageData DownloadPage(string websiteUrl)
        {
            WebClient client = new WebClient();
            WebPageData data = new WebPageData() { URL = websiteUrl };

            data.PageContents = client.DownloadString(data.URL);
            return data;
        }

As the code is the debugger throws an error when i == Pages.Length == 3.

I've tried changing i < Pages.Length to i < Pages.Length - 1, which result in the loop being finished, but a null exception later in the code (expected).

I've also tried putting in if(i >= Pages.Length) break into the loop, but it had no effect for some reason.

Arc2066
  • 183
  • 7
  • 1
    `tasks[i] = Task.Run(() => DownloadPage(Pages[i]));` is effectively `tasks[i] = Task.Run(() => DownloadPage(Pages[Pages.Length]));` (note `Pages[Pages.Length]`). See the linked question for an explanation for why this happens. – ProgrammingLlama Oct 29 '19 at 06:42
  • 1
    Thanks for the link. Just changed the code and that fixed it. Also greetings from Osaka. – Arc2066 Oct 29 '19 at 06:51

0 Answers0