C # - the index was outside the array using the same list sizes in a loop

I am creating a file loader in .NET that downloads an array of files from a server using asynchronous tasks. However, although I create Task[]and returned string[]with the same length.

Here is my method:

    public static string[] DownloadList(string[] urlArray, string[] toPathArray, string login = "", string pass = "", bool getExt = false)
    {
        Console.WriteLine("DownloadList({0}, {1}, {2}, {3}, {4})", urlArray, toPathArray, login, pass, getExt);
        try {
            returnedArray = new string[urlArray.Length];
            Task[] taskArray = new Task[urlArray.Length];
            for (int i = 0; i < urlArray.Length; i++)
            {
                Thread.Sleep(1000);
                Console.WriteLine("i = {0}", i);
                Task task = new Task(() => { returnedArray[i] = Download(urlArray[i], toPathArray[i], login, pass, getExt, true); });
                task.Start();
                taskArray[i] = task;
            }
            Task.WaitAll(taskArray);
            Thread.Sleep(1000);
            Console.WriteLine();
            Console.WriteLine("Done! Press Enter to close.");
            Console.ReadLine();
            return returnedArray;
        }
        catch(Exception e)
        {
            Console.WriteLine();
            Console.WriteLine(e.Message);
            Console.ReadLine();
            return null;
        }
    }

and exception:

exception

which points to this line:

exception line

I know that it will be something stupid that I missed, but I rattled my brain, trying to figure it out. Thanks for the help in advance!

+4
source share
3 answers

It looks like a problem Access to modified closure . Copy ito local variable:

for (int i = 0; i < urlArray.Length; i++)
{
    int index = i;
    Thread.Sleep(1000);
    Console.WriteLine("i = {0}", index );
    Task task = new Task(() => { returnedArray[index] = Download(urlArray[index], toPathArray[index], login, pass, getExt, true); });
    task.Start();
    taskArray[index] = task;
}
+8
source

@ . , .Net, foreach, . , :

foreach(var i in Enumerable.Range(0, urlArray.Length))
{
    ... new Task(() => { returnedArray[i] = ...
}

.

+2

It looks like you have exceeded the array by one, because you are counting the length of the array in the loop and 10, and the array from 0 to 9.

 for (int i = 0; i < urlArray.Length; i++)

Must be

 for (int i = 0; i < urlArray.Length - 1; i++)
-1
source

Source: https://habr.com/ru/post/1677922/


All Articles