Exception about SoftwareBitmapSource in UWP Code

0

What's wrong with this code?

private async void FrameMonitor_PartEvent(object sender, MonitorParam monitorParam)
    {
        SoftwareBitmap bmp = new SoftwareBitmap(BitmapPixelFormat.Bgra8, (int)monitorParam.WP_FrameInfo.ImageWidth, (int)monitorParam.WP_FrameInfo.ImageHeight, BitmapAlphaMode.Ignore);
        IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(monitorParam.WP_FrameBytes);
        bmp.CopyFromBuffer(buffer);
        SoftwareBitmapSource bmpsource = new SoftwareBitmapSource();
        await bmpsource.SetBitmapAsync(bmp);
        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () =>
        {

            Img_WPImg.Source = bmpsource;           
        });
        bmp.Dispose();
    }

On this code:

SoftwareBitmapSource bmpsource = new SoftwareBitmapSource();

Visual Studio shows this exception:

System.Exception: 'The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'

I hope there is a master hand can help me.

uwp
win-universal-app
uwp-xaml
asked on Stack Overflow Nov 15, 2017 by X.Huang • edited Nov 15, 2017 by Pedro Lamas

1 Answer

0

That exception tells me that you need to do that from the UI thread, so just move that code inside the Dispatcher, like this:

private async void FrameMonitor_PartEvent(object sender, MonitorParam monitorParam)
{
    SoftwareBitmap bmp = new SoftwareBitmap(BitmapPixelFormat.Bgra8, (int)monitorParam.WP_FrameInfo.ImageWidth, (int)monitorParam.WP_FrameInfo.ImageHeight, BitmapAlphaMode.Ignore);
    IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(monitorParam.WP_FrameBytes);
    bmp.CopyFromBuffer(buffer);
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () =>
    {
        SoftwareBitmapSource bmpsource = new SoftwareBitmapSource();

        await bmpsource.SetBitmapAsync(bmp);

        Img_WPImg.Source = bmpsource;           
    });
    bmp.Dispose();
}
answered on Stack Overflow Nov 15, 2017 by Pedro Lamas

User contributions licensed under CC BY-SA 3.0