Tuesday, December 8, 2009

Updating WPF window from background thread

I like to do things in the background--you know, you've got a long-running process, so you don't want to bother the user while it runs.

But you want to notify the user when the process is done.  Trouble is, since the background process is running in a different thread from the user interface, the process crashes if you make any attempt to update the user interface directly.

Here's some sample code to solve this with the Dispatcher--kind of well known, but nice to document anyhow:


void UpdateText(string text)
{
    if (this.Dispatcher != System.Windows.Threading.Dispatcher.CurrentDispatcher)
    {
        this.Dispatcher.Invoke(new Action(Update), text);
    }
    else
    {
        this.sampleTextBox.Text = text;
    }

}

2 comments:

  1. More common solution is probably to use a delegate as member of class that creates thread. ;-)

    ReplyDelete
  2. That's basically what is being done in that initial post. Nothing different than your comment.

    ReplyDelete