2012-01-09 72 views
1

我知道你需要使用Dispatcher從工作者線程更新UI線程中的項目。爲了確認我的理解,當你得到與當前對象關聯的Dispatcher時,如果我的類繼承自UserControl類,它總是UI調度程序?在哪些情況下不是UI調度程序?Silverlight中不會導致交叉線程異常?

無論如何,在下面的代碼中,我創建了一個查詢並以異步方式啓動它,當它完成時,它將itemsource設置爲我的一個UI元素。我還將項目添加到UI元素用作其itemsource的可觀察集合中。當它運行時,它可以正常工作,並且不用擔心使用調度程序並以這種方式更新UI。這是爲什麼?

private void UserControl_Loaded(object sender, RoutedEventArgs e) 
{ 
    QueryTask queryTask = new QueryTask(URL); 
    queryTask.ExecuteCompleted += new EventHandler<QueryEventArgs>(queryTask_ExecuteCompleted); 
    queryTask.Failed += new EventHandler<TaskFailedEventArgs>(queryTask_Failed); 
    Query query = new Query(); 
    query.Where = "Field <> 'XXX'"; 
    query.OutFields.Add("*"); 
    queryTask.ExecuteAsync(query); 
    BuildingsOrganizationList.ItemsSource = organizationList; 
} 


void queryTask_ExecuteCompleted(object sender, QueryEventArgs e) 
{ 
    FeatureSet featureSet = e.FeatureSet; 
    foreach (KeyValuePair<string, string> columns in featureSet.FieldAliases) 
    { 
     TypeGrid.Columns.Add(new DataGridTextColumn() 
     { 
      Header = columns.Key, 
      Binding = new System.Windows.Data.Binding("Attributes[" + columns.Key + "]"), 
      CanUserSort = true 
     }); 
    } 
    TypeGrid.ItemsSource = featureSet.Features; 
    TypeBusyIndicator.IsBusy = false; 

    testing(); 
} 

private void testing() 
{ 
    List<string> temp = new List<string>(); 
    temp.Add("Item 1"); 
    temp.Add("Item 2"); 
    temp.Add("Item 3"); 

    foreach (string org in temp) 
    { 
     organizationList.Add(org); 
    } 
} 
+0

如果您想從另一個線程更新您的用戶界面,必須使用調度程序。 ExecuteCompleted是一個回調函數,你不會從它正在運行的線程之外觸及你的UI。 – Alex 2012-01-09 14:58:31

回答

2

因爲即使處理異步完成後,您檢索您的UI線程的結果(未將事件線程),並從那裏進行更新。

但是,如果你把裏面queryTask_ExecuteCompleted代碼的任務:

Task.Factory.StartNew(() => 
{ 
    //code of queryTask_ExecuteCompleted here 
}); 

你會得到你的異常。

+0

那麼爲什麼我在網上看到的很多文章都說在Silverlight中進行異步調用時使用Dispatcher。像這樣:http://www.silverlightshow.net/items/Tip-Asynchronous-Silverlight-Execute-on-the-UI-thread.aspx – Justin 2012-01-09 14:55:32

+0

如果您要更新您的ExecuteAsync中的用戶界面,則必須使用調度程序方法。你不這樣做,所以你不需要它。您的事件處理程序已經在您的UI線程上。 – 2012-01-09 14:57:31

+0

你能給我一些需要使用調度程序的代碼的例子嗎? – Justin 2012-01-09 15:06:40

1

ExecuteCompleted事件發生在調用ExecuteAsync的同一線程上。

相關問題