I am trying to use multithreading to call this function. When I run the program I get an exception "Index out of range". When I try to print the values of 'i' I get serviceids list.count each times.
In my case the loop should go from 0 to 1 and print The value of i this time is 0 The value of i this time is 1
but it prints both times
The value of i this time is 2 The value of i this time is 2
What is wrong with my code and how can I fix it ? DataDownloader downloader = new DataDownloader();
for (int i = 0; i < serviceidslist.Count; i++)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(
delegate(object o, DoWorkEventArgs argss)
{
BackgroundWorker b = o as BackgroundWorker;
Console.WriteLine("The value of i this time is {0}", i);
downloader.DoDownload(serviceidslist[i]);
});
bw.RunWorkerAsync();
}