Windows 8 Development–When Your UI Thread is not Your Main Thread

This is something that someone raised with me today and I thought I’d write it down because I noticed it when I first came to developing with .NET on Windows 8 and WinRT and it threw me for about an hour or so which perhaps lets me save you from spending an hour or so on it in the future.

Thinking from a .NET perspective, if you go into Visual Studio and make a new project as in;

image

and you let Visual Studio instantiate that template then build the project (CTRL+SHIFT+B) and then use the Solution Explorer (CTRL+ALT+L) to use the “Show All Files” button;

image

and then have a look in your debug\obj folder for a file called App.g.i.cs;

image

and jump to that method Main and set a breakpoint;

image

Now open up your App.xaml.cs file and find it’s method OnLaunched;

image

and put a breakpoint there and finally open up your MainPage.xaml.cs file and find it’s method OnNavigatedTo;

image

and put a breakpoint there. Run the application with F5 and when you land on the first breakpoint, use the Debug->Windows->Threads menu option to ensure that you can see what your threads are doing.

Here’s my breakpoint in Main;

image

and there’s not a lot there that’s going to surprise you – I have a single main thread that has called Main and it’s all as expected.

Here’s my breakpoint in OnLaunched;

image

and there is something there that might surprise you. We are not on our Main Thread but, instead, we are on a Worker Thread (8428) which is different from what you’d expect to see (I think) if you were coming from a WPF or Windows Forms background.

If we have a look at the current SynchronizationContext in the Watch window;

image

then we’ll notice that this is set up so (by default) any await work that we do can make use of that SynchronizationContext and if we continue on to our next breakpoint in OnLaunched we’ll notice that we are on the same Worker Thread (8428) that we were in OnLaunched.

So…take a little care when you’re debugging this applications because the assumption that I used to make which was Main Thread == UI Thread is not necessarily the case here so don’t let that lead you off down the wrong path as it did with me when I first saw it.