相当于WPF中的InvokeRequired

在WPF中是否存在与Form.InvokeRequired等效的内容,例如Dispatcher.InvokeRequired?

这有点奇怪,因为它没有出现在intellisense中,但你可以使用:

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

由于所有UI组件都inheritance自DispatcherObject因此这应解决您的特定问题,但它并非特定于UI线程 – 它可用于任何调度程序。

相当于Dispatcher.CheckAccess 。

想到一个可能的解决方案是:

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

如果您正在构建Windowsapp store应用,则上述示例将不起作用。 这是一个有效的例子。 根据需要修改,当然:)

 ///  /// Updates the UI after the albums have been retrieved. This prevents the annoying delay when receiving the albums list. ///  ///  public void UpdateUiAfterAlbumsRetrieved(System.Collections.ObjectModel.ObservableCollection 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; } }