Creating BitmapImage on background thread WP7
I'm receiving an UnauthorizedAccessException ("Invalid cross-thread access.") when running the following code on a background (threadpool) thread, is this expected behaviour?
var uri = new开发者_如何学运维 Uri("resourcevault/images/defaultSearch.png", UriKind.Relative);
var info = Application.GetResourceStream(uri);
// this line throws exception....
this.defaultSearchImage = new BitmapImage();
The reason is because your background thread cannot directly be used to update the UI. Instead, you need to use a Dispatcher
to marshal the data on to the UI thread. Something like this:
var uri = new Uri("resourcevault/images/defaultSearch.png", UriKind.Relative);
var info = Application.GetResourceStream(uri);
Dispatcher.BeginInvoke(() => {
this.defaultSearchImage = new BitmapImage();
});
精彩评论