4

我正在构建一个 WP8 应用程序,它使用来自 Internet 的图像更改锁屏的背景。我按照计划代理和锁屏上的教程进行操作,但我遇到了问题。

当我尝试从 Scheduled Agent 下载新的背景图像时,我得到了这个:

+       $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 不起作用,如何将图像保存在计划代理中?我正在做“跨线程访问”是什么意思?图像仅由预定代理创建和使用,因此任何人都不应访问它们。

4

1 回答 1

6

问题源于 BitmapImage 无法在 UI 线程之外实例化。您可以通过将调用包装在 Dispatcher Invoke 调用中来解决此问题。

但是,您需要确保正确调用 NotifyComplete。因此,您可能需要将 NotifyComplete 放入 Dispatcher 调用中。

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

来源:在隔离存储上工作时调度代理上的无效交叉异常

于 2012-12-14T13:22:40.597 回答