一段很简答的,模拟多任务并发的测试代码。
private void button_Click(object sender, EventArgs e)
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 30; i++)
{
//匿名函数 闭包捕获变量index
int index = i;
actions.Add(new Action(() => {
Console.WriteLine("task List step1 :" + index);
Thread.Sleep(2000);
Console.WriteLine("task List step2 :" + index);
}));
index = i + 1;
}
Console.WriteLine("Parallel.Invoke before");
Parallel.Invoke(actions.ToArray());
Console.WriteLine("Parallel.Invoke after");
}