Exiting a Windows Phone Application

<UPDATE>
Turns out that the Application Certification Requirements 4.2.5 expressly disallows calling any methods in the Microsoft.Xna.Framework.Game and .Graphics assemblies when your application uses any methods from the System.Windows.Controls namespace. So using the method below in an application that you intend to publish will cause it to be rejected.
</UPDATE>

So, I started working on a WP7 application with a friend recently and I really wanted to do test first, which makes me more comfortable, and my favorite test framework is Machine.Specifications (MSpec). Unfortunately MSpec doesn't exist for WP7 or Silverlight, so I spent the weekend porting it over.

As I was working on the test runner I wanted to run the tests, post the results to a listening result-display application running on the desktop and quit the runner. It turns out, however, that there is no way to quit a WP7 application, and that this was by design.

It looks like people are doing (as was alluded to by Peter's article) is throwing an exception of a specific type and not handling it in the UnhandledException handler for the application. This is effective if not a little dirty, though this could be an issue if in the future Microsoft starts providing crash reports to developers.

I found a slightly cleaner way to do this, and since it's a very uncommon use-case I think it's a decent compromise. In Peter's article, besides throwing an exception, he says that XNA games calling Game.Exit() is the only other way for programatically exiting an application running on the phone.

So simply add a reference to the Microsoft.Xna.Framework.Game assembly to your WP7 Silverlight app and then anywhere that you want to exit just execute this one-liner.

new Microsoft.Xna.Framework.Game().Exit();

This quickly and effectively terminates the application, and since Microsoft.Xna.Framework.Game.dll is included in the ROM on the device you don't need to worry about it bloating your application. Though, I haven't tried submitting an application to the marketplace that actually uses this method so YMMV.