0

我嘗試使我的ListBox連接到ObservaleCollection效率更高,因此對於DB查詢,我實現了一個BackgroundWorker來完成這項工作。然後,在這個背景工作者,我想添加每個可以說的70毫秒3條目的用戶界面,所以更大數量的條目(可以說100)的用戶界面不會被阻止。 下面是代碼:BackgroundWorker中的收集處理

void updateTMWorker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     var MessagesInDB = from MessageViewModel tm in MessagesDB.Messages 
            where tm.Type.Equals(_type) 
            orderby tm.Distance 
            select tm; 

     // Execute the query and place the results into a collection. 
     Dispatcher.BeginInvoke(() => { MessagesClass.Instance.Messages = new ObservableCollection<MessageViewModel>(); }); 

     Collection<MessageViewModel> tempM = new Collection<MessageViewModel>(); 
     int tempCounter = 0; 

     foreach (MessageViewModel mToAdd in MessagesInDB) 
     { 
      if (MessagesClass.Instance.Messages.IndexOf(mToAdd) == -1) 
      { 
       tempM.Add(mToAdd); 
       tempCounter = tempCounter + 1; 
      } 
      if (tempCounter % 3 == 0) 
      { 
       tempCounter = 0; 
       Debug.WriteLine("SIZE OF TEMP:" + tempM.Count()); 
       Dispatcher.BeginInvoke(() => 
       { 
        // add 3 messages at once 
        MessagesClass.Instance.Messages.Add(tempM[0]); 
        MessagesClass.Instance.Messages.Add(tempM[1]); 
        MessagesClass.Instance.Messages.Add(tempM[2]); 
       }); 
       tempM = new Collection<MessageViewModel>(); 
       Thread.Sleep(70); 
      } 
     } 
     // finish off the rest 
     Dispatcher.BeginInvoke(() => 
     { 
      for (int i = 0; i < tempM.Count(); i++) 
      { 
       MessagesClass.Instance.Messages.Add(tempM[i]); 
      } 
     });    
    } 

的輸出是:

SIZE OF TEMP:3 

A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll 
在線路

:MessagesClass.Instance.Messages.Add(tempM [0]);代碼試圖訪問tempM的第一個元素

任何提示什麼是錯的?爲什麼我不能訪問tempM元素,儘管集合大小> 0?

回答

1

你忘了線程同步。看看你的代碼:

  1: Debug.WriteLine("SIZE OF TEMP:" + tempM.Count()); 
      Dispatcher.BeginInvoke(() => 
      { 
       // add 3 messages at once 
       3: MessagesClass.Instance.Messages.Add(tempM[0]); 
       MessagesClass.Instance.Messages.Add(tempM[1]); 
       MessagesClass.Instance.Messages.Add(tempM[2]); 
      }); 
      2: tempM = new Collection<MessageViewModel>(); 

tempM當執行MessagesClass.Instance.Messages.Add(tempM[0]);已經將null。因此,使用某種排序或同步對象,例如:

  EventWaitHandle Wait = new AutoResetEvent(false); 

      Debug.WriteLine("SIZE OF TEMP:" + tempM.Count()); 
      Dispatcher.BeginInvoke(() => 
      { 
       // add 3 messages at once 
       MessagesClass.Instance.Messages.Add(tempM[0]); 
       MessagesClass.Instance.Messages.Add(tempM[1]); 
       MessagesClass.Instance.Messages.Add(tempM[2]); 

       Wait.Set(); 
      }); 
      // wait while tempM is not in use anymore 
      Wait.WaitOne(); 

      tempM = new Collection<MessageViewModel>(); 
+0

謝謝。這解決了我的問題。不知怎的,我需要更熟悉線程同步。 :)請致電 – webaloman

+0

,將答案標記爲已接受 – Ku6opr