Reputation: 337
i want to finish is that : user can dynamic create a tab page , and for each tab page , it will contain a corresponding thread do working .
what i do is :
1 : in main window 's "create tab page" button , add below code :
currentUserControl = new everyTabPage();
TabPage tp = new TabPage();
tp.Name = "a";
tp.Controls.Add(currentUserControl);
currentUserControl.Dock = DockStyle.Fill;
tabControl1.TabPages.Add(tp);
everyTabPage is a user control like this picture
2 : in this userControl 's "start" button , add
Thread tM = new Thread(new ParameterizedThreadStart(ThreadFunc));
tM.IsBackground = true;
tM.Start(comboBox1.Text);
and this is the thread function , for testing , i only change the label 's text.
public void ThreadFunc(object param)
{
string SessionParameter = (string)param;
while (true)
{
this.Invoke((MethodInvoker)delegate()
{
label1.Text = DateTime.Now.ToString() + @"_" + SessionParameter;
});
}
}
3 : after doing these , now program seems work as i wanted .
but when i testing it , i find if i create more than three tabs , program 's speed will become very very slow .
consider now i only change the label 's text , it already so slow , if i realy do some business work , the speed will not acceptable .
can anybody tell me why the speed is so slow , or if my solution is not effective ,thanks .
Upvotes: 0
Views: 303
Reputation: 1076
Do you really Need the
while(true)
I think if you only want to set the Label text then you do not Need it.
while(true)
Needs a lot of CPU time e.g.
Upvotes: 0
Reputation: 127603
It is slow because although ThreadFunc
runs on a separate thread that Invoke
you perform does all the work from all your threads on the UI thread so you are flooding the UI thread with messages and it can not get any work done.
Does your program really need to update the UI in that tight of a loop? A better option may be to use a Timer
and have the updates happen on the timer elapsed event instead.
A another quick fix instead of using a timer is put a sleep in the loop.
public void ThreadFunc(object param)
{
string SessionParameter = (string)param;
while (true)
{
this.Invoke((MethodInvoker)delegate()
{
label1.Text = DateTime.Now.ToString() + @"_" + SessionParameter;
});
Thread.Sleep(250);
}
}
Now your UI will update 4 times a second instead of 400,000 times a second.
Upvotes: 1