Reputation: 1159
I want to execute methods in parallel without starting a new thread or a new Task for each method. I am using Winforms
and targeting .Net 4.5
Here's what I want to do. I have a List named accounts, method called processAccount
, and I want to start processAccount
for each account in the list. I want to execute the methods in parallel and after quite some reading it looks like Parallel.Invoke
might be what I need:
List<string> accounts = new List<string>();
private static void processAccount(string acc)
{
//do a lot of things
}
Action[] actionsArray = new Action[accounts.Count];
//how do I do the code below
for (int i = 0; i < accounts.Count; i++)
{
actionsArray[i] = processAccount(accounts[i]); // ?????
}
//this is the line that should start the methods in parallel
Parallel.Invoke(actionsArray);
Upvotes: 1
Views: 107
Reputation: 32296
The problem is that you need to create an Action. The easiest way to do that is with a lambda.
for (int i = 0; i < accounts.Count; i++)
{
int index = i;
actionsArray[i] = () => processAccount(accounts(index));
}
Note that you have to capture the i
variable inside the loop in the index
variable so that all the actions don't end up using the same value, that would end up being accounts.Count
after the for
loop finishes.
Upvotes: 4