I am not too familiar with C# and I need to implement multithreading by creating 5 threads. However, I keep getting an error:
Run-time exception (line 20): Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
I am not changing the list at all during program execution, so I'm not sure why I keep getting this error. Here's my code:
using System;
using System.Threading;
using System.Collections.Generic;
namespace Parallelization{
public class Update{
//creating a lock object of reference type
private Object LOCK = new Object();
public void StartGroup(){
Console.WriteLine("Restoring groups");
List<string> Groups = GetGroupsName();
//parallelizing vm groups
Thread[] threads = new Thread[Groups.Count];
//create a new thread for each vm group
for(int i = 0; i < Groups.Count; i++){
threads[i] = new Thread(() => StartParallel(Groups[i]));
Console.WriteLine("Starting thread {0}", I); //ERROR
}
for(int i = 0; i < Groups.Count; i++){
threads[i].Start();
}
}
//callback for each thread
private void StartParallel(string GroupName){
try{
//Restore group
lock(LOCK){
RestoreGroup(GroupName);
}
}
catch(Exception ex){
Console.WriteLine("Exception encountered! restoration failed");
}
}
//function to restore each vm group
private void RestoreGroup(string GroupName){
Console.WriteLine(GroupName + " restored!");
}
//function to obtain a list of group names
private List<string> GetGroupsName(){
List<string> groups = new List<string>
{"group1","group2","group3","group4","group5"};
return groups;
}
}
public class Groups{
//calling StartGroup
public static void Main(string[] args){
Update update = new Update();
update.StartGroup();
}
}
}