I have two recursive methods that follow one after the other, each generating data for each node to a tree of any size. (I cannot combine the two because the second is dependent on the first's results - also, the first iteration is from leaf to root and the second, root to leaf.) I need to generate the data for every node addition/position update. I need to draw the tree to a cached bitmap every tree status update.
I currently am using a BackgroundWorker for this, but when the user adds a numerous amount of nodes, things start to lag as if the task was working on the same thread as the UI. (This is the first time I've used a BackgroundWorker but not for handling threads in general)
I came across Matt's post once: BackgroundWorker vs background Thread Should I revert back to a System.Thread instead or may their be another option? I need to store the resulting tree and an integer value on the main thread when the process is finished.
[Threading]
private void Commence()
{
if (worker.IsBusy)
{
try
{
// I was thinking of fixing this with a timer instead
worker.CancelAsync();
while (worker.IsBusy) Thread.Sleep(10);
}
catch { return; }
}
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
// int radMax; TreeNodeEx rTNH;
// Call the two recursive methods
radMax = GenerateDataFromNodes(rTNH, radMax);
UpdateRenderRegion(); // draw result to cached bitmap
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// draw bitmap to screen
if (!e.Cancelled) Invalidate();
}
[Algorithm]
private int GenerateDataFromNodes(TreeNodeEx hierarchy, int max)
{
// set hierarchy values
max = GenerateScaleAndRadius(hierarchy, max);
GenerateStartAndSweep(hierarchy);
return max;
}
private int GenerateScaleAndRadius(TreeNodeEx hierarchy, int max, int radius = 2)
{
for (int i = 0; i < hierarchy.Nodes.Count; i++)
{
max = GenerateScaleAndRadius((TreeNodeEx)hierarchy.Nodes[i], max, radius+1);
}
// generation a
return max;
}
private void GenerateStartAndSweep(TreeNodeEx hierarchy)
{
for (int i = 0; i < hierarchy.Nodes.Count; i++)
{
// generation b-1
}
}
private void node_SweepAngleChagned(object sender, EventArgs e)
{
for (int i = 0; i < ((TreeNode)sender).Nodes.Count; i++)
{
// generation b-2
}
}
[Invalidation]
private void UpdateRenderRegion()
{
if (rTNH != null)
{
renderArea = new Bitmap(radMax * rScale * 2, radMax * rScale * 2);
Graphics gfx = Graphics.FromImage(renderArea);
gfx.SmoothingMode = SmoothingMode.AntiAlias;
// pens, graphicspaths, and pathgradients
// draw parent first
// draw generations next using the same structure as the parent
DrawNodes(gfx, p, rTNH, rScale, w, h);
gfx.Dispose();
}
}