我有一个树结构,为此我正在使用此类:
class Node
{
long IdNode;
List<Node> Childs;
string path;
Data data;
}
路径是以“。”开头的IdNode,因此,节点的路径为“IdParent.IdNode”,依此类推。因此,要设置节点的路径,我需要父节点的路径。
我有这种方法:
public setPath(Node paramParentNode)
{
this.path = paramParentNode.Path + "." + this.IDNode;
foreach(Node iteratorNode in this.Childs)
{
iteratorNode.setPath(this);
}
}
这是一个保密版本。但是我在考虑如何并行实现这一点,就像这样:
public setPathMt(Node paramParentNode)
{
this.path = paramParentNode.Path + "." + this.IDNode;
Parallel.Foreach(this.Childs,
(iteratorNode) =>
{
iteratorNode.SetPathMt(this);
}
);
}
但是我不知道这是否正确,因为我不知道如何等待该方法的递归调用,我的意思是,我如何知道递归方法何时完成。
哪一种是实现该方法的多线程递归方法的最佳方法?
谢谢。
最佳答案
你的方法应该像
public SetPath(Node paramParentNode)
{
paramParentNode.Path = paramParentNode.Path + "." + this.IDNode;
foreach(Node iteratorNode in paramParentNode.Childs)
{
SetPath(iteratorNode);
}
}
和这样的并行方法
public SetPathMt(Node paramParentNode)
{
paramParentNode.Path = paramParentNode.Path + "." + this.IDNode;
Parallel.Foreach(paramParentNode.Childs,
new ParallelOptions { MaxDegreeOfParallelism = 32 },
(iteratorNode) =>
{
SetPathMt(iteratorNode);
}
);
}
您根本没有使用在方法中传递的节点。当您使用
this
时,它表示该类的实例,在所有递归方法中都将保持不变。唯一改变的是方法中的参数传递。new ParallelOptions { MaxDegreeOfParallelism = 32 }
将此并行操作使用的并发操作(线程)数限制为32(可以是您想要的数字)或-1(所有可用线程)。