Search code examples
wpfdispatcherbegininvoke

Question about WPF Dispatcher.BeginInvoke called from same thread! Why?


I'm relatively new to WPF. I'm examining some code that looks like this:

private void button_Click(object sender, RoutedEventArgs e)
{
    //Queue on dispatcher in the background so it doesn't make the UI slow
        Dispatcher.BeginInvoke(new dMyDelegate(PerformOperation), DispatcherPriority.Background);
}

From the comment, I'm guessing the original code felt that this was necessary to make the UI more responsive, however, my understanding is that Dispatcher.BeginInvoke simply runs something on the UI thread. Since the buttn_Click is already on the UI thread, what's the point? Perhaps I'm misunderstanding Dispatcher and BeginInvoke. I'm assumming that Dispatcher in this case, is the dispatcher owned by the class this method is in, which is MainWindow.xaml. Can someone enlighten me?

Thanks


Solution

  • Well, it's asking for "background" priority, so it's only going to get executed when any more important events have been processed... If this is part of a big screen refresh, it'll effectively wait until all of that has happened before executing. Even so, if it's going to be doing anything long-running (or making any potentially blocking calls) then you're right, it really shouldn't be running on the UI thread at all.