- Sanket Mistry
In Part 2, we saw essential controls to use while developing
Windows Store Application. In this article we will be touching some core
fundamentals of Windows store. We shall look at Application Life Cycle in
Window Store since, that is something new and as a developer one should
carefully handle it. Then we will take a look at application I made during my
learning on Windows Store App. At last we will see new keyword supported by C#
i.e. async.
App Life Cycle and State
In Windows 8, you can launch a bunch of apps and switch
between them without having to worry about slowing down the system or running
the battery down. That's because the system automatically suspends (and
sometimes terminates) apps that are running in the background for you. A
well-designed app can be suspended, terminated, and re-launched by the system
and seem as though it were running the entire time.

When you start your app it goes into running state. An app
can be suspended when the user switches away from it or when Windows enters a
low power state. While your app is suspended, it continues to reside in memory
so that users can quickly and reliably switch between suspended apps, resuming
them. When your app is suspended and then resumed, you don't have to write any
extra code to make it look as though it had been running the entire time. But
Windows can also terminate a suspended app at any time to free up memory for
other apps or to save power. When your app is terminated, it stops running and
is unloaded from memory.
When the user closes an app by pressing Alt+F4 or using the close
gesture, the app is suspended for 10 seconds and then terminated. Windows
notifies your app when it suspends it, but doesn't provide additional
notification when it terminates the app. That means your app must handle the
suspended event and use it to save its state and release its exclusive
resources and file handles immediately.
To create a good user experience, you want your app to look
like it never stopped running. The app needs to retain any data the user
entered, settings they changed, and so on. That means you need to save your
app's state when it's suspended, in case Windows terminates it, so that you can
restore its state later. There are two types of data for you to manage in your
app: app data and session data. Windows Store provides an API for managing the
same via SuspendManager. We will see
how we can use it in Windows Store App.
When you create new Windows Store Application, IDE will
automatically add following line that will make App enabled for saving/loading
state.
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
HelloWorld.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");
...
Windows provides a Windows.Storage.ApplicationData
object to help you manage your app data. This object has a RoamingSettings property that returns an ApplicationDataContainer. You can use this ApplicationDataContainer to store app data that persists across
sessions. Let's store the user's name in the roaming ApplicationDataContainer as the user types it in.
1.
Windows.Storage.ApplicationDataContainer
roamingSettings =
2.
Windows.Storage.ApplicationData.Current.RoamingSettings;
3.
roamingSettings.Values["EmailAddress"]
= emailInput.Text;
4.
Session data is temporary data that is relevant to the
user’s current session in your app. A session ends when the user closes the app
using the close gesture or Alt + F4, reboots the computer, or logs off the
computer. You restore it only if Windows suspends and terminates the app. You
need to save the navigation state of the app Frame, so the app can be restored
to the same page is was on, and so the SuspensionManager
knows which page to restore the state of. You also need to save the state of
the page itself. This is where you save the date. You use the SuspensionManager class to save session
state in the Application.Suspending
event handler.
When you create new Windows Store App, It creates
SuspensionManager class for you, so you would not have to remember all these
really. However, it is up to us to decide what part of App data you would like
to store. Yes, we have save the state now, but How to restore it? Let’s take a
look at restoring data we saved.
Once, your app gets activated, you can restore App State
from LoadState in each page.
1.
protected override void LoadState(Object navigationParameter, Dictionary<String,
Object> pageState)
2.
{
3.
//
Restore values stored in session state.
4.
if (pageState != null && pageState.ContainsKey("greetingOutputText"))
5.
{
6. greetingOutput.Text =
pageState["greetingOutputText"].ToString();
7.
}
8.
9.
//
Restore values stored in app data.
10. Windows.Storage.ApplicationDataContainer
roamingSettings =
11.
Windows.Storage.ApplicationData.Current.RoamingSettings;
12. if (roamingSettings.Values.ContainsKey("userName"))
13.
{
14.
nameInput.Text =
roamingSettings.Values["userName"].ToString();
15.
}
16. }
17.
As shown above, you can then restore state from RoamSettings/Localsettings.
OK, Now we have done saving state and loading state. But How to de test it? We
can do so by simulating states from Visual Studio.
You can test various state and its transition directly. This
gives developer a good control over App and its Life Cycle. Once must be very careful in choosing what
amount of Data to save inside date.
Async is your partner!
Windows Store App is always about user experience. And
Microsoft is promoting usage of async as and when required in Windows Store
Application.
The async modifier indicates that the method, lambda
expression, or anonymous method that it modifies is asynchronous. Such methods
are referred to as async methods. An async method provides a convenient way to
do potentially long-running work without blocking the caller's thread. The
caller of an async method can resume its work without waiting for the async
method to finish. Typically, a method modified by the async keyword contains at
least one await expression or statement. The method runs synchronously until it
reaches the first await expression, at which point it is suspended until the
awaited task is complete. In the meantime, control is returned to the caller of
the method. If the method does not contain an await expression or statement,
then it executes synchronously. I found nice simple example on MSDN for using
async.
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>. (See "Return Types" section.)
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}
In order to call async method, you may use await keyword as
shown below.
string urlContents = await client.GetStringAsync();
The await operator is applied to a
task in an asynchronous method to suspend the execution of the method until the
awaited task completes. The task represents ongoing work. The task to which the
await operator is applied typically is the return value from a call to a method
that implements the Task-Based
Asynchronous Pattern. Examples include values of type Task or Task<TResult>.