Mike Taulty's Blog
Bits and Bytes from Microsoft UK
Windows 8 Development–When Your UI Thread is not Your Main Thread


Mike Taulty's Blog



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;


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;


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


and jump to that method Main and set a breakpoint;


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


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


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;


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;


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;


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.

Posted Thu, Aug 30 2012 9:52 AM by mtaulty
Filed under: , , ,


John Michael Hauck wrote re: Windows 8 Development–When Your UI Thread is not Your Main Thread
on Thu, Aug 30 2012 2:01 PM


I ran into this same problem from a slightly different angle - and I even submitted it as a bug to MSFT! I blogged about it in May 2012 and sound this great article by Stephen Toub: blogs.msdn.com/.../10259049.aspx.

- John

DotNetKicks.com wrote Developing Windows 8 - When your main thread is not your UI thread
on Thu, Aug 30 2012 2:59 PM

You've been kicked (a good thing) - Trackback from DotNetKicks.com