views:

42

answers:

1

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

+1  A: 

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.

Jon Skeet
Ahhh. I didn't focus on the second parameter. That makes sense. "PerformOperation" will get called after all the normal priority events. Somewhere else in the code they also call BeginInvoke with "background" and have a not about letting the GUI redraw first. Do you happen to know what level the redrawing of the screen is? That is if I block and unblock the app with MSWord or minimize and maximize? Is it "normal" or higher? Finally, it would seem that once PerformOperation does start, the GUI is locked out? Correct?
Dave
@Andrew: I'm afraid I don't know about priorities... but yes, once PerformOperation starts, the dispatcher thread will be locked out. I believe there's a separate render thread, which may avoid getting a blank screen, but I don't know much about the details there.
Jon Skeet
Thanks! Marked as answer.
Dave