Windows Phone 8.1 - 从后台任务创建 WriteableBitmap 时出现异常

Posted

技术标签:

【中文标题】Windows Phone 8.1 - 从后台任务创建 WriteableBitmap 时出现异常【英文标题】:Windows Phone 8.1 - Exception when creating WriteableBitmap from a Background Task 【发布时间】:2015-01-18 15:23:28 【问题描述】:

我正在构建一个 Windows Phone 8.1 应用程序(Windows 运行时,而不是 Windows Phone Silverlight 8.1)。我创建了一个使用维护触发器触发的后台任务。在后台任务中,我需要从一张相机胶卷图片创建一个 WriteableBitmap。我的代码如下:

public sealed class Class1 : IBackgroundTask

    public async void Run(IBackgroundTaskInstance taskInstance)
    
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

        var files = await KnownFolders.CameraRoll.GetFilesAsync();

        ShowNotification("Process has started");

        using(var fileStream = await files[0].OpenStreamForReadAsync())
        
            WriteableBitmap writeableBitmap = await BitmapFactory.New(1, 1).FromStream(fileStream.AsRandomAccessStream());
        

        ShowNotification("Process has ended");

        deferral.Complete();
    

当我运行后台任务时,两个通知按预期工作,但出现以下异常:

"A first chance of exception of type "System.Exception" occurred in WriteableBitmapEx.WinRT.DLL""
"A first chance of exception of type "System.Exception" occurred in mscorlib.dll"

"The proccess has ended with code 1 (0x1)"

如果我删除这些行:

using(var fileStream = await files[0].OpenStreamForReadAsync())

    WriteableBitmap writeableBitmap = await BitmapFactory.New(1, 1).FromStream(fileStream.AsRandomAccessStream());

一切都按预期工作,出现 2 个通知并且没有抛出异常。

有什么想法吗?

谢谢。

【问题讨论】:

异常信息是什么? 我想知道WritableBitmap是否只能在UI线程(后台任务没有)上实例化/使用? 是的,据我所知位图只能在 UI 线程上完成! 那么,不可能在BackgroundTask上创建WriteableBitmap? 异常消息是:应用程序调用了一个为不同线程编组的接口。 (来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD)) 【参考方案1】:

使用XamlRenderingBackgroundTask 在后台生成 XAML 图形。请注意,建议您为此使用 C++,以尽量减少内存使用。

【讨论】:

以上是关于Windows Phone 8.1 - 从后台任务创建 WriteableBitmap 时出现异常的主要内容,如果未能解决你的问题,请参考以下文章

在 Windows Phone 8.1 中的时间触发后从后台任务唤醒/启动主应用程序

可以运行 2 个后台任务 - Windows Phone 8.1 通用应用程序?

Windows phone 8.1 后台任务内存管理

Windows phone 8.1 后台任务突然退出

Windows Phone 8.1 后台任务 - 无法调试且不会触发

Geofence windows phone 8.1中触发后台任务的阈值距离