Equivalent to InvokeRequired in WPF

前端 未结 4 1306
死守一世寂寞
死守一世寂寞 2021-02-15 23:02

Is there an equivalent to Form.InvokeRequired in WPF, e.g. Dispatcher.InvokeRequired?

相关标签:
4条回答
  • 2021-02-15 23:23

    If you're building a Windows Store app, the above example won't work. Here's an example that does work. Modify as needed, of course :)

    /// <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;
        }
    }
    
    0 讨论(0)
  • 2021-02-15 23:42

    The equivalent is Dispatcher.CheckAccess.

    0 讨论(0)
  • 2021-02-15 23:44

    This is slightly odd as it doesn't appear in intellisense, but you can use:

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

    As all UI components inherit from DispatcherObject this should solve your specific problem, but it is not specific to the UI thread - it can be used for any dispatcher.

    0 讨论(0)
  • 2021-02-15 23:45

    A possible solution that came to mind is:

    if ( Dispatcher.Thread.Equals( Thread.CurrentThread ) )
    {
        Action( );
    }
    else
    {
        Dispatcher.Invoke( Action );
    }
    
    0 讨论(0)
提交回复
热议问题