4

我正在構建一個WP8應用程序,它使用來自Internet的圖像更改鎖定屏幕的背景。我遵循預定代理和鎖屏界面上的教程,但我遇到了問題。從預定代理程序保存圖像時System.UnauthorizedAccessException

當我嘗試從計劃的代理下載新的背景圖像,我得到這個:

+  $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} 

的代碼是:

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); 
    } 
} 

我真的不知道如何解決這個。如果BitmapImage不起作用,如何將圖像保存在計劃代理中?這是什麼意思,我正在做「跨線程訪問」?這些圖像僅由計劃的代理創建和使用,因此沒有人應該訪問它們。

回答

6

問題出在BitmapImage無法在UI線程之外實例化的事實。您可以通過將調用包裝在Dispatcher Invoke調用中來解決此問題。

但是,您需要確保您正確調用NotifyComplete。因此,您可能需要將NotifyComplete置於分派器調用中。

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

來源:Invalid Cross Exception on Schedule Agent when working on isolated storage

+0

謝謝!對我感到羞恥,我甚至認爲我可以在計劃任務中使用分派器。現在就像一個魅力...除了由於圖像大小的小System.OutOfMemoryException。 ;) – blueocean