0

I’m writing a method which will download files from both LAN shared and FTP Shared directories. I have list of multiple vendors. I am using tasks to achieve this. But I am getting ArrayIndexOutofBond Exception. Although my loop condition is right?

Here is code segment.

 vendorWiseTasksListening = new List<Task>();
                    for (int i = 0; i < allVendorIDs.Length; i++)
                    {
                        Task task = new Task(() => FTPMode(allVendorIDs[i]));
                        vendorWiseTasksListening.Add(task);
                        task.Start();
                        task = new Task(() => SharedMode(allVendorIDs[i]));
                        vendorWiseTasksListening.Add(task);
                        task.Start();
                    }
                    Task.WaitAll(vendorWiseTasksListening.ToArray());

Any help would be appreciated.

arrowd
  • 33,231
  • 8
  • 79
  • 110
Sheraz
  • 567
  • 4
  • 22
  • Well, unless your shared objects are made smart enough to be thread safe ... they are not thread safe which means you get errors accessing them from multiple threads. – TomTom Apr 11 '16 at 06:46
  • So how can i make sure that they become thread safe? – Sheraz Apr 11 '16 at 06:48
  • 2
    Locking of SOME sort. Programming in a way that does not require shared objects and does the collection at the end. LOCKING is easiest (read up the lock keyword). At the end: you ask us to teach you programming. Too broad. – TomTom Apr 11 '16 at 06:54
  • 1
    Learn about thread safety. http://stackoverflow.com/questions/11623039/how-to-make-objects-threadsafe-on-c/11623449 – L-Four Apr 11 '16 at 06:57

1 Answers1

2

Your problem might be, that the value of you variable i is NOT saved once you create the new task, but all your tasks use a reference to the same variable i. And this i is incremented until allVendorIDs.Length.

If some Task accesses the value of i after the loop in the main thread has finished, it will get allVendorIDs.Length.

Make a local copy of i and use this in your tasks:

 for (int i = 0; i < allVendorIDs.Length; i++)
                {
                    int j = i;
                    Task task = new Task(() => FTPMode(allVendorIDs[j]));
                    vendorWiseTasksListening.Add(task);

                    task.Start();
                    task = new Task(() => SharedMode(allVendorIDs[j]));
                    vendorWiseTasksListening.Add(task);
                    task.Start();
                }

See for example this question for a simpler example and explanation.

Community
  • 1
  • 1
Jens
  • 25,229
  • 9
  • 75
  • 117