2

我一直在尝试并行化以下函数,但不知道如何去做。

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 个线程已经在运行等待输入,我可以向其分派每个调用。

我习惯了并行循环的正常范式,不知道如何处理这个(至少不是以干净的方式)。

4

1 回答 1

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();
    }

}
于 2012-08-26T10:04:15.343 回答