Note on using the BitmapImage and Image classes in C# Windows 10 UWP applications: these objects must be created in the main thread

Posted: (EET/GMT+2)

 

In Windows 10 UWP programming, there are a couple of caveats that are related to threading. Shortly put, certain classes, especially those displaying something on the user interface, must be created (constructed) on the main thread of the application.

This rule applies to the BitmapImage and Image classes, among others. If you try to construct new instances of these classes, you will get a System.Exception with a message similar to this:

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

The solution is to create object instances on the main thread instead. But what if you want to create new instances of these classes inside a task (Task.Factory.StartNew for example)? You can use a little help from the dispatcher, available on all windows and frames.

The dispatcher has a convenient RunAsync method that allows you to run code in the main thread, even if called from within a task. Here's an example:

// start a new background task
Task.Factory.StartNew(async () =>
{
    // do some work here
    // ...

    // use the dispatcher to get back to the main thread
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
        // example: create an image object
        Image image = new Image();
        image.Width = 400;
        image.Height = 300;
        image.Source = bitmap;
    });
    
    // return back to the task context, run some more code
    // ...
});

Hope this helps!