Tuesday, March 15, 2011

WPF: How to handle errors with a BackgroundWorker

I am a bit of a newbie when it comes to windows client programming. I have a background worker that has a DoWork event and a RunCompleted event wired up. If an exception gets thrown in DoWork, I want to make changes to my UI, however, I cant because it is in a different thread. I can communicate the error to RunCompleted, but that doesn't help me either.

From stackoverflow
  • call Dispatcher.BeginInvoke. Basically, you want code like this:

    void UpdateState(WhatEverType someObject)
    {
        if (! Dispatcher.CheckAccess())
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(()=>UpdateState(someObject));
        }
        else
        {
            //make the UI changes here.
        }
    }
    
    Matt Briggs : Very good answer, I like the way it calls itself through the dispatcher. Thank you :)

0 comments:

Post a Comment