我一直试图并行化以下功能,但无法弄清楚如何使用。
public static Cell GetClosestCell (Cell cell)
{
// The four calls below should be run in parallel.
Cell temp1 = new FindNorth(cell);
Cell temp2 = new FindSouth(cell);
Cell temp3 = new FindWest(cell);
Cell temp4 = new FindEast(cell);
// Return smallest cell based on [X].
if ((temp1.X < temp2.X) && (temp1.X < temp3.X) && (temp1.X < temp4.X))
{
return (temp1);
}
else if ((temp2.X < temp3.X) && (temp2.X < temp4.X))
{
return (temp2);
}
else if (temp3.X < temp4.X)
{
return (temp3);
}
else
{
return (temp4);
}
}
四个函数调用中的每一个都应该并行运行,而不必启动线程。换句话说,应该有4个线程已经在运行,等待我可以调度每个调用的输入。
我已经习惯了并行循环的常规范例,并且不确定如何处理这种情况(至少不是以干净的方式)。
答案 0 :(得分:2)
using System;
using System.Threading.Tasks;
public class Program {
public static void Main() {
Task<Cell> task1 = new Task<Cell>(n => FindNorth((Cell)n), cell);
Task<Cell> task2 = new Task<Cell>(n => FindSouth((Cell)n), cell);
Task<Cell> task3 = new Task<Cell>(n => FindSouth((Cell)n), cell);
Task<Cell> task4 = new Task<Cell>(n => FindEast((Cell)n), cell);
task1.Start();
task2.Start();
task3.Start();
task4.Start();
Console.WriteLine("Main method complete. Press <enter> to finish.");
Console.ReadLine();
}
}