|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionSometimes we have to present really large You would think that filling up the Background: MultithreadingIn only a few words, multithreading makes it possible to run several tasks parallel. We would like to use our controls on the form -edit a With this solution, we use BackgroundWorker that is a library class for multithreading. The Problem: Simple Multithreading Does Not WorkThe easiest way would be simple multithreading: public void FillTree()
{
for (int i = 0; i < 10; i++)
{
tn = treeView1.Nodes.Add(i.ToString());
for (int j = 0; j < 10; j++)
{
tn.Nodes.Add(((int)(i * 10 + j)).ToString());
System.Threading.Thread.Sleep(100);
}
}
}
private void Form2_Load(object sender, EventArgs e)
{
System.Threading.Thread th = new System.Threading.Thread(FillTree);
th.Start();
}
The only problem with this solution is that it does not work. We get an The Trick: Multithreading & InvokeIn the previous section, we realised that we need more than simple multithreading. We get an exception if we try to add a node to the To execute an operation in the treeView1.Invoke(new Add(Add1), new object[] { i });
public delegate void Add(int i);
Now our solution works as follows: when the form is opening, we start to run the Start the new thread with private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
Call the filling subroutine in the background thread (we have to handle private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FillTree();
}
The filling subroutine calls back to the public void FillTree()
{
for (int i = 0; i < 10; i++)
{
treeView1.Invoke(new Add(Add1), new object[] { i });
for (int j = 0; j < 10; j++)
{
treeView1.Invoke(new Add(Add2), new object[] { i * 10 + j });
}
}
}
For more details, please see the attached source code. History
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||