Seva Alekseyev
Seva Alekseyev

Reputation: 61388

WrongThreadException in WinRT async handler

WinRT project, C++/CX. I'm trying to load a PNG file into a WriteableBitmap. I'm setting the Source property to an IRandomAccessStream. To get a stream from file, one has to use an async operation - there's no sync file open in WinRT.

My async completion handler is executed, it seems, on a random worker thread. And in that handler, the most innocent operations (like constructing a new WriteableBitmap) cause a WrongThreadException. It's not reproducible from run to run.

What's going on? Should I chalk it up to pre-release funkiness?

Visual Studio 2012 RC, Windows 8 build 8400.

Upvotes: 0

Views: 538

Answers (1)

Larry Osterman
Larry Osterman

Reputation: 16142

When you interact with UI elements, they need to be performed on the UI thread. The easiest way of ensuring that you're on the UI thread is to use the PPL continuations - if you use the create stream async APIs, then the lambda passed to the ".then" method should run in the thread context of the original thread - usually the UI thread.

If you can't get back to the UI thread via PPL, then use CoreDispatcher.RunAsync() and do your work in the lambda passed to RunAsync - that will always run on the UI thread.

Upvotes: 1

Related Questions