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
我希望并行执行方法,而无需为每个方法启动新线程或新任务。我正在使用Winforms并以.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:
这就是我想要做的。我有一个名为accounts的列表,名为processAccount的方法,我想为列表中的每个帐户启动processAccount。我想并行执行这些方法,经过一些阅读后看起来像Parallel.Invoke可能是我需要的:
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);
1 个解决方案
#1
The problem is that you need to create an Action. The easiest way to do that is with a lambda.
问题是你需要创建一个Action。最简单的方法是使用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.
请注意,您必须在索引变量中捕获循环内的i变量,以便所有操作都不会使用相同的值,最终在for循环结束后成为accounts.Count。
#1
The problem is that you need to create an Action. The easiest way to do that is with a lambda.
问题是你需要创建一个Action。最简单的方法是使用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.
请注意,您必须在索引变量中捕获循环内的i变量,以便所有操作都不会使用相同的值,最终在for循环结束后成为accounts.Count。