4

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();
AwkwardCoder
  • 24,893
  • 27
  • 82
  • 152

1 Answers1

2

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();
});
keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • 1
    thanks, it appears you can only create BitmapImage classes on the UI thread, this makes sense really because it is only going to be used by the UI and is intrinsically tied to the UI... – AwkwardCoder Jun 29 '11 at 10:08
  • @AwkwardCoder - Yup, anytime you need to manipulate a UI element (instantiation or update), then it has to be done on the UI thread. – keyboardP Jun 29 '11 at 10:12
  • in XAML there is – Agent_L Aug 16 '12 at 14:25
  • 1
    @Agent_L - Sorry, I'm not following. What part remains unanswered? The `CreateOptions` attribute was introduced to make it easier to set the decoding process to occur on a background thread, rather than the UI thread. However, once the decoding decoding is complete, it still returns to the UI thread, where it is displayed. – keyboardP Aug 16 '12 at 15:20
  • yeah, but here everything (including decoding) is done in UI thread. – Agent_L Aug 16 '12 at 15:59
  • 1
    Everything before the BeginInvoke line in the code above is occurring on a background thread. The assignment has to occur on the UI thread. – keyboardP Aug 16 '12 at 16:56
  • There's nothing related to the bitmap done before Dispatcher. All computation-heavy creation and decoding is done on UI thread. – Agent_L Oct 26 '12 at 11:36
  • 1
    @Agent_L - Background Creation was the default setting at the time of that post. Mango SDK was in beta. http://blogs.msdn.com/b/slmperf/archive/2011/06/13/off-thread-decoding-of-images-on-mango-how-it-impacts-you-application.aspx – keyboardP Oct 26 '12 at 11:49
  • @Agent_L No problem. I think you have to explicitly set it now as it was causing problems with some apps that were created before version 7.1. – keyboardP Oct 29 '12 at 00:04