我的以下代码在其他应用程序中运行良好。
在我的应用程序中,我有 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参数决定的所以线程1传0,线程2传1
最佳答案
我认为 60 毫秒和 4 个异步线程对 UI 消息管道来说是一个很大的负载,所以它卡住了。如果从应用程序行为要求的角度来看合适,请尝试增加时间间隔(例如 200 毫秒)。
顺便说一句,您可以如下所示引用 switch 语句,这样代码会更加清晰:
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);
}
}
}
}
关于c# - 多个线程向 ListBox 添加和删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8242269/