2012-03-01 24 views
5

我在backgroundworker上做了一些繁重的工作,因此它不會影響我的Silverlight UI線程。但是,在DoWork功能中,我收到以下異常:在不訪問UI線程的情況下在BackgroundWorker中獲取「UnauthorizedAccessException」

UnauthorizedAccessException「無效的跨線程訪問」。

我知道我不能從BackgroundWorker的訪問UI線程,然而,在這條線出現此異常:

ListBoxItem insert = new ListBoxItem(); 

如何在訪問我的UI線程?

下面是我縮小到的一段代碼。我基本上做的工作創造listboxitems我想插入到sourceList列表框:

void FillSourceList() 
{ 
    busyIndicator.IsBusy = true; 
    BackgroundWorker bw = new BackgroundWorker(); 
    bw.DoWork += (sender, args) => 
     { 
      List<ListBoxItem> x = new List<ListBoxItem>(); 
      for (int i = 0; i < 25; i++) 
      { 
       ListBoxItem insert = new ListBoxItem(); //<---Getting exception here 
       insert.Content = "whatever"; 
       x.Add(insert); 
      } 
      args.Result = x; 
     }; 
    bw.RunWorkerCompleted += (sender, args) => 
     { 
      foreach (ListBoxItem insert in (List<ListBoxItem>)(args.Result)) 
       sourceList.Items.Add(insert); 
      busyIndicator.IsBusy = false; 
     }; 

    bw.RunWorkerAsync(); 
} 

回答

4

一個ListBoxitem從Control派生,因此被認爲是GUI的一部分。我希望在一個線程中有一個「獨立」的項目也可以,但顯然不是。

顯而易見的解決方案:建立Content(字符串)的列表x並延遲Items到Completed事件的創建。

+0

謝謝。是的,這似乎有點不必要,但不是很好,但有趣。我在'ListBoxItem'上做了一些基於內容的處理,比如着色,所以我不能簡單地創建字符串..但是,我想我會管理打包我需要的信息到一個KeyValuePair中,直到它們創建。 – 2012-03-01 14:39:25

+0

你可以考慮一個迷你的ViewModel的項目。只需將一個列表綁定到ItemsSource並設置好,包含線程安全。 – 2012-03-01 14:45:44

+0

好主意!我可能會那樣做,不應該爲項目的其餘部分需要太多的改變(我希望;)。 – 2012-03-01 14:59:52

相關問題