我有以下代码,在其他应用程序中运行良好。
在我的应用程序中,有4个线程每60毫秒调用AddToList方法。
一旦列表中达到1000个项目并开始尝试删除项目,则CPU使用率会达到100%。将计数设置为100会解决此问题。
有任何想法吗?
以下是代码:
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;
}
}
更新: 仅为澄清,第一个线程将仅更新Listbox1,第二个线程将更新Listbox2。这是由InputID参数决定的,因此Thread1传递0,Thread 2传递1。