I am using the MVVM pattern to develop a WPF application.
The app loads a captcha image from the server, and assigns it to an Image on the WPF form when ready. I am using a BackgroundWorker to do the threading for me, as follows:
When the Window is being loaded, the following is called:
BackgroundWorker _bgWorker = new BackgroundWorker();
_bgWorker.DoWork += GetCaptchaImage;
_bgWorker.RunWorkerAsync();
The GetCaptchaImage function is fairly simply, loading an image in another thread:
BitmapSource _tempBitmap = GetCaptchaFromServer();
I need to know how to Invoke the Dispatcher to assign this ImageSource to my Window's image source, Currently I call the dispatcher after loading the _tempBitmap as follows:
Application.Current.Dispatcher.Invoke(
new Action(() => CaptchaBitmap = _tempBitmap));
Where CaptchaBitmap is databound to my image source.
However, when I do this, an InvalidOperationException is thrown, and any reference to _tempBitmap returns an error in the GUI thread. I know its because I am accessing it from the dispatcher GUI thread, when it was created in a BackgroundWorker thread, but how do I get around it?
Help would be greatly appreciated! :)