In a WPF application I'm writing, I have a TransformedBitmap property which is bound to an Image object on the UI. Whenever I change this property, the Image is updated (and thus the image being displayed to the screen is updated). In order to prevent the UI from freezing or becoming unresponsive whilst I retrieve the next image, I'm attempting to the snapshot retrieval with a BackgroundWorker like this:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = this.snapshotHelper.GetSnapshot(ImageFormat.Bmp);
}
then, in my RunWorkerCompleted method, I have the following:
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.CurrentImage = (TransformedBitmap)e.Result;
....
}
This seems to work okay until on the NotifyPropertyChanged method used to tell the Image object to update when I update the CurrentImage property; I get a cross-thread error.
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
//The following causes a "the calling thread cannot access this object because a different thread owns it" error!
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
I really don't know how to change things around or what to do differently to get around this error. I've been reading about BackgroundWorkers for the past couple of hours and it seems to me that I should be able to set CurrentImage fine in the RunWorkerCompleted method; at least from what I can tell. Any help on this would be greatly appreciated! Thanks!