How to traverse a tree (class containing parent and child properties of the same class) using threads?
-
Hi, Having a class with parent child relationships is quite common (I think), and I normally traverse such trees using recursion. Class looks like this:
public class Product {
public List Parents {get; set;}
public List Children {get; set;}
public string Name {get; set;}
public override string ToString() { return Name; }
}Recursion will look like this:
public void Dump(Product p) {
Console.WriteLine(p.ToString());foreach (var child in p.Children) Dump(child); // (1)
}
However, I was told by someone before that using threads will be faster and less expensive. Can anyone send me a sample code of how to do this? I'm thinking that I should simply change (1) to a
ParameterizedThreadStart
... but maybe there's a better practice? Thanks in advance.Rafferty
-
Hi, Having a class with parent child relationships is quite common (I think), and I normally traverse such trees using recursion. Class looks like this:
public class Product {
public List Parents {get; set;}
public List Children {get; set;}
public string Name {get; set;}
public override string ToString() { return Name; }
}Recursion will look like this:
public void Dump(Product p) {
Console.WriteLine(p.ToString());foreach (var child in p.Children) Dump(child); // (1)
}
However, I was told by someone before that using threads will be faster and less expensive. Can anyone send me a sample code of how to do this? I'm thinking that I should simply change (1) to a
ParameterizedThreadStart
... but maybe there's a better practice? Thanks in advance.Rafferty
In fact, the person that told you this does not know the final step of your application or he tried to impress you :) You may have multiple threads in order to travers the tree, but in your case, the problem will be the output (Console.Writeline(....)) which is thread safe, you will have a lock in order to block multiple threads to access the output buffer. So, except if you are sure that you have a multiple core, in order millions of data (but in this case do not use the Console), I advise you to stay thread safe (1 thread and this one will catch the maximum of CPU) or otherwise you wil have a timce slice handling to do and lock/unlock to manage. You should have a good start with: Generic Background Worker[^] Good luck