我有下面的代码,在其他应用程序中正常工作。多个线程添加和删除项目到列表框
在我的应用程序中,我有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;
}
}
}
UPDATE:只是为了澄清。第一个线程只会更新Listbox1,第二个线程会更新Listbox 2.这是由InputID参数决定的,所以Thread1传递0和Thread 2传递1
你是说,你叫从多个线程的代码?该代码不是线程安全的,首先检查计数,然后调用remove(另一个线程可能同时添加/删除了某些内容)?但这不是性能问题的根源。 –
@Anders Invoke将其序列化。线程安全不是问题。 –
这听起来像你可能会更好地与虚拟模式下运行的列表框(或列表视图),但是这是在WinForms中实现的。 –