2011-10-14 49 views

回答

5

,因爲它沒有在智能感知出現,這是有點奇怪,但你可以使用:

var dispatcher = myDispatcherObject.Dispatcher; 
if (dispatcher.CheckAccess()) { /* ... */ } 

由於所有UI組件繼承從DispatcherObject這應該解決您的具體問題,但它不是特定於UI線程 - 它可以用於任何調度程序。

3

來考慮可能的解決方案是:

if (Dispatcher.Thread.Equals(Thread.CurrentThread)) 
{ 
    Action(); 
} 
else 
{ 
    Dispatcher.Invoke(Action); 
} 
0

如果您正在構建Windows應用商店應用,則上述示例將不起作用。這裏有一個例子,確實工作。根據需要修改當然:)

/// <summary> 
/// Updates the UI after the albums have been retrieved. This prevents the annoying delay when receiving the albums list. 
/// </summary> 
/// <param name="albums"></param> 
public void UpdateUiAfterAlbumsRetrieved(System.Collections.ObjectModel.ObservableCollection<PhotoAlbum> albums) 
{ 
    if (!Dispatcher.HasThreadAccess) 
    { 
     Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => 
     { 
      ddlAlbums.DataContext = albums; 
      ddlAlbums.IsEnabled = true; 
      tbxProgress.Text = String.Empty; 
      ProgressBar.IsIndeterminate = false; 
      ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed; 
     }); 
    } 
    else 
    { 
     ddlAlbums.DataContext = albums; 
     ddlAlbums.IsEnabled = true; 
     tbxProgress.Text = String.Empty; 
     ProgressBar.IsIndeterminate = false; 
    } 
}