WP7: Writing a Well-Behaved Threaded Application

The latest CTP release of Windows Phone 7 introduces a new managed library which exposes events you can monitor to catch changes in state in your application. The assembly is Microsoft.Phone.Execution.dll. This contains a WindowsPhoneEvents class which exposes two static methods – Pause and Resume. You can handle these events to detect when your application is dismissed and reactivated. This allows you to stop unnecessary processing and be a good citizen. I put together a simple example which shows how to pause a background thread based on these events and you can see the results by running it on the Emulator and switching to the home screen (Windows button) and returning to your application (Back button).

The sample uses a ManualResetEvent to block the background thread to avoid it consuming processor cycles while the app is paused. (22kb)


Also in this assembly is the StreamPersister class. Unfortunately there is no documentation for this at the moment but an instance is passed in the Pause and Resume eventargs which will presumably allow you to safely persist state data which you can then load when your app is resumed. Hopefully there will be some official documentation on this to complete the picture.

By Peter Freeman Foot

Microsoft Windows Development MVP