2011-11-23 65 views
3

我有下面的代碼,在其他應用程序中正常工作。多個線程添加和刪除項目到列表框

在我的應用程序中,我有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

+0

你是說,你叫從多個線程的代碼?該代碼不是線程安全的,首先檢查計數,然後調用remove(另一個線程可能同時添加/刪除了某些內容)?但這不是性能問題的根源。 –

+0

@Anders Invoke將其序列化。線程安全不是問題。 –

+0

這聽起來像你可能會更好地與虛擬模式下運行的列表框(或列表視圖),但是這是在WinForms中實現的。 –

回答

1

我相信60毫秒和4個異步線程對UI消息管道,所以它卡住了。如果從應用程序行爲需求的角度來看這是合適的,則嘗試增加時間間隔(例如200毫秒)。

順便說一句,您可以refcator 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); 
      } 
     } 
    } 
} 
+0

謝謝。我無法控制輸入的速度。我知道它相隔60毫秒,但降低計數固定它出於某種原因 – Jon

+0

@Jon:基本上你是在列表的開頭添加一條新消息,然後刪除最後一個項目?順便說一句,你正在使用哪種控制類型?你能給全名包括名字空間嗎? – sll

+0

一旦達到一定的限制,是的。它是一個System.Windows.Forms.ListBox – Jon

相關問題