System.UnauthorizedAccessException when saving image from scheduled agent

I am creating a WP8 application that changes the screen lock background using images from the Internet. I followed tutorials on planned agents and Lockscreen, but I have a problem.

When I try to download a new background image from the Scheduled Agent, I get the following:

+ $exception {System.UnauthorizedAccessException: Invalid cross-thread access. at MS.Internal.XcpImports.CheckThread() at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex, IntPtr constructDO) at System.Windows.Media.Imaging.BitmapImage..ctor() at TileLockAgent.ScheduledAgent.lockScreenClient_OpenReadCompleted(Object sender, OpenReadCompletedEventArgs e) at System.Net.WebClient.OnOpenReadCompleted(OpenReadCompletedEventArgs e) at System.Net.WebClient.OpenReadOperationCompleted(Object arg) at System.Threading.WaitCallback.Invoke(Object state) at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()} System.Exception {System.UnauthorizedAccessException} 

Code:

 string fileName; try { var currentImage = LockScreen.GetImageUri(); if (currentImage.ToString().EndsWith("_1.jpg")) { fileName = "LockBackground_2.jpg"; } else { fileName = "LockBackground_1.jpg"; } } catch { // lockscreen not set or prev owned by other app fileName = "LiveLockBackground_1.jpg"; } using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { var bi = new BitmapImage(); bi.SetSource(e.Result); var wb = new WriteableBitmap(bi); using (var isoFileStream = isoStore.CreateFile(fileName)) { var width = wb.PixelWidth; var height = wb.PixelHeight; Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100); } } 

I really don't know how to solve this. How to save an image in a scheduled agent if BitmapImage is not working? What does it mean that I am doing end-to-end access? Images are created and used only by the planning agent, so no one should contact them.

+4
source share
1 answer

The problem arises because BitmapImage cannot be created outside the UI thread. You can fix this problem by wrapping calls in a Dispatcher Invoke call.

However, you need to make sure that you correctly call NotifyComplete. In this case, you may need to add NotifyComplete to the Dispatcher call.

  Deployment.Current.Dispatcher.BeginInvoke(() => { UpdateSyncPictureName(...); NotifyComplete(); }); 

Source: Invalid cross exception in Schedule agent when running in isolated storage

+6
source

All Articles