gpt4 book ai didi

c# - 线程简单计算

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:44 25 4
gpt4 key购买 nike

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

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 个线程已经在等待输入,我可以将每个调用分派(dispatch)给它们。

我已经习惯了并行循环的正常范例,但不确定如何处理这个问题(至少不是以一种干净的方式)。

最佳答案

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

}

关于c# - 线程简单计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12129136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com