Reputation: 40062
I have the below code that works fine in other applications.
In my application I have 4 threads calling a AddToList method every 60ms.
Once it got to 1000 items in a list and began to try and remove items the CPU would go to 100%. Setting the count down to 100 would fix it.
Any ideas why?
Here is the code:
public delegate void dgAddToList(string Message, int InputID);
public void AddToList(string Message, int InputID)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new dgAddToList(AddToList), new object[] { Message, InputID });
}
else
{
switch (InputID)
{
case 0:
this.listBox1.Items.Insert(0, Message);
if (this.listBox1.Items.Count > 100)
this.listBox1.Items.RemoveAt(this.listBox1.Items.Count - 1);
break;
case 1:
this.listBox2.Items.Insert(0, Message);
if (this.listBox2.Items.Count > 100)
this.listBox2.Items.RemoveAt(this.listBox2.Items.Count - 1);
break;
case 2:
this.listBox3.Items.Insert(0, Message);
if (this.listBox3.Items.Count > 100)
this.listBox3.Items.RemoveAt(this.listBox3.Items.Count - 1);
break;
case 3:
this.listBox4.Items.Insert(0, Message);
if (this.listBox4.Items.Count > 100)
this.listBox4.Items.RemoveAt(this.listBox4.Items.Count - 1);
break;
}
}
}
UPDATE: Just to clarify. The first thread will only update Listbox1, the second thread will update Listbox 2. This is determined by the InputID parameter so Thread1 passes 0 and Thread 2 passes 1
Upvotes: 3
Views: 3862
Reputation: 62554
I believe 60 milliseconds and 4 async threads is a big load for UI messages pipeline so it got stuck. Try out increasing time interval (for instance 200 milliseconds) if this is appropriate from an application behaviour requirements perspectives.
BTW, You can refcator switch statement as shown below so code would be much clear:
public void AddToList(string Message, int InputID)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new dgAddToList(AddToList), new object[] { Message, InputID });
}
else
{
ListBox listBoxInstance = null;
switch (InputID)
{
case 0:
listBoxInstance = this.listBox1;
break;
case 1:
listBoxInstance = this.listBox2;
break;
case 2:
listBoxInstance = this.listBox3;
break;
case 3:
listBoxInstance = this.listBox4;
break;
}
if (listBoxInstance != null)
{
listBoxInstance.Items.Insert(0, Message);
if (listBoxInstance.Items.Count > 100)
{
listBoxInstance.Items.RemoveAt(
listBoxInstance.Items.Count - 1);
}
}
}
}
Upvotes: 1