(X) Hide this
    • Login
    • Join
      • Say No Bots Generate New Image
        By clicking 'Register' you accept the terms of use .

Windows 8 Metro: Something about application life-cycle

(8 votes)
Andrea Boschin
>
Andrea Boschin
Joined Nov 17, 2009
Articles:   91
Comments:   9
More Articles
18 comments   /   posted on May 21, 2012
Categories:   Windows 8 , General

Also if currently you are probably running Windows 8 on a virtual machine or luckily on a computer, there is not any doubt that this new operating system and especially the metro-style interface is dedicated to touch enabled devices like tablets. The plans of Microsoft infact include the new WOA keywork where the acronym stands for Windows On ARM that is the aim of making available this interface on a wide set of mobile devices that currently embrace this successful processor architecture.

Running on a tablet does not only imply a different input interface like the touch screen, but also it requires a careful use of system resources that are not always large on this kind of device. This is the reason why metro-style applications have an application lifecycle that is mostly similar to the Windows Phone than of classical desktop apps.

It is matter of life or suspension

As a user, when you start a desktop application, you are exactly aware of the boundaries of its life. You click the icon and the application starts, then you use it and finally you hit the close button and the application closes. There are nothing behind this common process but you, as the final user, are responsible to decide how many applications runs at the same time so the management of system resources is completely up to you. Also if the previous sentence oversimplifies the matter, since behind the scenes the operating system manages system resources in an optimal way, if you continue to open a number of apps, at a given point you reach the maximum of resources available and you get an error.

From the metro point of view, this scenario completely changes. The only thing you are exactly aware is the time when you start your application the very first time after you switched on your device, and from this point the lifetime of the application is completely up to the operating system. You can still choose to close a metro-style app but this is not exactly required nor favored. In metro guidelines is strongly stated that your application must not have a "close button" or such a way to close the application, under the penalty of failure of the certification for the marketplace. If the user choose to close the app he has to use a combination of ALT+F4 or the close gesture (swipe the screen from the top to the bottom). The most common way to go away from the current app is by pressing the start button that brings you to the start screen but this not really close the app.

imageThe rule is really simple: you can always have only one application running. You can hit the maximum of two apps running at the same time, only in a few cases, when one is snapped and the other runs as filled. In all the other states Windows only allows a single application to run, so probably this is the most common scenario. What it happens behind the scenes is that when you start an application it get its own space in terms of system resources and becomes the current running application, but when you hit start and move to another one, the application you are leaving is "suspended". This means the OS saves the current execution state and prevent the processor from continue to execute it; in this state the application resides in memory and continue to allocate the space assigned to it but it does not currently run.

To become aware of this process you can do a simple exercise using the Task Manager. First of all go to desktop and open the new Task Manager. Then activate the "Show suspended status" item in the View menu. imageThis let you see when an application enters the suspended state. Now return to the start screen and activate some applications. Finally you have to return to desktop by pressing the WindowsKey+D and watch at the task manager. The situation you will see is almost similar to the one in the figure on the side where you have a number of apps in suspended state and a single that results to be running. But waiting 10 seconds also last application enters the suspended state. Windows works in a smart way. When the user leave an application it waits a few before to switch it to suspended because there is a chance the user returns to the application immediately. After 10 seconds passed, the operating system move the app to the suspended state but does not remove it from the memory. This enable the user to switch rapidly from an app to another since Windows only need to activate and deactivate the app without loading it from the disk.

This works fine until the systems has lot of resources. But obviously if you continue to run new apps, you reach a moment when the system needs to free some space to ensure a good feedback to the user. In this case Windows can decide to terminate some of the applications that are currently suspended. After the app has been terminated all the resources are freed and Windows can only starts it again from scratch.

The developer point of view

Since the process I described above may seems completely automatic, there are some points that a developer must know to improve the feedback of the application.  After you created your application, it works also if you do anything about the lifetime management. The problem is that, especially in the case of termination, you have to take a decision about the experience you want for your user. If you do not handle this situation what the user will see it that randomly the application suddenly is reset and he loses the work he is doing. Windows is really careful in handling termination of the apps but when it finally goes on this way only the intervention of your code can save a situation that differently is like a complete shutdown.

To handle termination you have to act subtly. When Windows decide for the termination, it immediately releases all the resources without waiting nor notifying the application. As a developer the termination is completely transparent and when it happens it is too late to do anything. Differently you may assume that the termination happens only when the application has been suspended so the best it to act during suspension to save the state of the work as if the application is being terminated.

Starting to speak about code, the Application type is all what you need to handle this situation. As you know the App class defined in App.xaml.cs directly inherits from Application. So in this class you can attach some events to detect state changes:

OnLaunched: it is called every time the application is activated. This event, only available as override, happens when the application start from scratch on the first run or after being terminated. Remember that from the point of view of the operating system both these scenario are identical. The difference comes from the value of PreviousExecutionState you get in the arguments. This may be "NotRunning" or "Terminated".

Suspending: This event may be subscribed to get notified about the suspension of the application. You have to be aware that, when this even has been called you only have a few seconds to act to preserve the current state of the application. If you take long than 5 seconds Windows will assume that the application has crashed so terminate it.

Resuming: The resuming event is raised only when the application is reactivated after being suspended. Pay attention that resuming does not happen if the application is terminated.

OnActivated: This event is raised when the application is not activated normally. Since the normal activation raises OnLaunched, in other cases (a search, share, etc...) this event is called and you can user the ActivationKind enumeration to understand the reason. Also be aware of a number of methods that are specific to a single activation reason: OnSearchActivated, OnShareTargetActivatedm etc...

Reading carefully the events meaning, it becomes clear that there is two points where you have to handle the suspension. The first is the Suspending event. In this event you have to save the current state (loaded documents, fields, position of elements and so on...) to a persistent storage. The ApplicationData store is perfect for this purpose:

   1: public App()
   2: {
   3:     InitializeComponent();
   4:     this.Suspending += new SuspendingEventHandler(OnSuspending);
   5: }
   6:  
   7: protected void OnSuspending(object sender, SuspendingEventArgs args)
   8: {
   9:     SuspendingDeferral deferral = null;
  10:  
  11:     try
  12:     {
  13:         deferral = args.SuspendingOperation.GetDeferral();
  14:  
  15:         // save here the application state
  16:     }
  17:     finally
  18:     {
  19:         deferral.Complete();
  20:     }
  21: }

Thanks to the SuspendingDeferral instance, returned by the call to SuspendingOperation.GetDeferral, you can inform the runtime that the application is saving its data. Then the call to the Completed method confirm that the application is ready to be suspended. The use of the deferral does not give you additional time. The limit of 5 seconds is still valid.

When the application is resumed without being terminated you have nothing to do. In this case the situation is completely handled by Windows. So you have only the responsibility of handle the OnLaunched event an check if the app has been restored by a terminations instead fo begin started from scratch:

   1: protected override void OnLaunched(LaunchActivatedEventArgs args)
   2: {
   3:     var rootFrame = new Frame();
   4:     this.EnsureInitialized(rootFrame, args);
   5:     rootFrame.Navigate(typeof(MainPageView));
   6: }
   7:  
   8: private void EnsureInitialized(Frame rootFrame, IActivatedEventArgs args)
   9: {
  10:     if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
  11:     {
  12:         // restore the state here
  13:     }
  14:  
  15:     Window.Current.Content = rootFrame;
  16:     Window.Current.Activate();
  17: }

Thanks to the IActivatedEventArgs interface the EnsureInitialized method can be used also in case of different activations. As an example, if th app is started by a Search request, you need to threat the application state like in the case it starts normally. You can write the following code:

   1: protected override void OnSearchActivated(SearchActivatedEventArgs args)
   2: {
   3:     var rootFrame = new Frame();
   4:     this.EnsureInitialized(rootFrame, args);
   5:     rootFrame.Navigate(typeof(SearchGridPageView), args.QueryText);
   6: }

Now the point is: how can I persist the state? The right place is the application data store. This store is mostly known as IsolatedStorage in Silverlight and Windows Phone. For metro-style apps this storage has a number of additional features but for now it suffice you know that it can receive your files as a normal filesystem restricted to your app only. For this purpose the best is searching the SDK examples. In most of the XAML examples there is a SuspensionManager class that already implements all you need to save the application state. The important part using this class is to ensure the data you need do store is serializable using the DataContractSerializer. This means to decorate the classes with DataContractAttribute and DataMemberAttribute.

   1: [DataContract]
   2: public class ApplicationState
   3: {
   4:     [DataMember]
   5:     public int Number { get; set; }
   6:     [DataMember]
   7:     public string Name { get; set; }
   8: }

Then you have to add the types to the KnownTypes collection:

   1: public App()
   2: {
   3:     this.InitializeComponent();
   4:     this.Suspending += OnSuspending;
   5:  
   6:     SuspensionManager.KnownTypes.Add(typeof(ApplicationState));
   7: }

At this point you have to manage to save the state to the SuspensionManager and reload these information when it is required. It is important you avoid to restore the state if you are in the case of a fresh start because the guidelines express indicate it as a worst practice. Instead you have to handle the start from a termination:

   1: private void BlankPage_Loaded(object sender, RoutedEventArgs e)
   2: {
   3:     if (SuspensionManager.SessionState.ContainsKey("State"))
   4:     {
   5:         ApplicationState state = SuspensionManager.SessionState["State"] as ApplicationState;
   6:  
   7:         if (state != null)
   8:         {
   9:             this.theName.Text = state.Name;
  10:             this.theNumber.Text = state.Number.ToString();
  11:         }
  12:     }
  13: }
  14:  
  15: private void OkButton_Click(object sender, RoutedEventArgs e)
  16: {
  17:     SuspensionManager.SessionState["State"] = new ApplicationState
  18:     {
  19:         Name = this.theName.Text,
  20:         Number = int.Parse(this.theNumber.Text)
  21:     };
  22: }

Finally you have to add the SaveAsync and LoadAsync method calls to the Suspending and OnLaunched events. This methods use the DataContractSerializer to serialize and deserialize the SuspensionManager content and use the Aplication data store to persist it as a file.

Debugging suspension

imageIf you try to observe the lifecycle of an application that is running in debug mode, you will understand that under these conditions there is something different. When an application is debugged it is never suspended, so it is hard to debug the suspension and resume phases. For this purpose in Visual Studio 11 there is a small toolbar useful for this purpose. These buttons can simulate suspension and termination of the application and in this case your breakpoins are honored.

The suspension and resume in Windows 8 is important to give a better experience to the user, thaks to the optimization of the system resources. In the next article in the series I will write about another arpect that has the same direction: the asyncronicity and how to deal with it.


Subscribe

Comments

  • FabianMonclus

    Re: Windows 8 Metro: Something about application life-cycle


    posted by FabianMonclus on Jan 07, 2013 02:04
    Excellent, I help solve my problem. Thank you very much from Argentina
  • ChadFonger

    Re: Windows 8 Metro: Something about application life-cycle


    posted by ChadFonger on Dec 04, 2014 01:22

    Taking the bus to your destination can be a combersom way to get around when you have things to do like appointments or parties.  Just use the new way to get around from Lyft: 

  • ChadFonger

    Re: Windows 8 Metro: Something about application life-cycle


    posted by ChadFonger on Dec 04, 2014 01:54

    Eventually everyone tries out new technology and services in their local area.  In big cities people have the chance to try out taxi like services such as Lyft.  A good description how the service works here: 

  • ChadFonger

    Re: Windows 8 Metro: Something about application life-cycle


    posted by ChadFonger on Dec 04, 2014 04:29
  • TanveerAliKhan

    Re: Windows 8 Metro: Something about application life-cycle


    posted by TanveerAliKhan on Mar 31, 2015 22:26

    Pagerank can are priced between 0-10, 0 may be the lowest score practical for a web page, while 10 is the better. The bigger the pr of a web-site with both receiving more visitors. use this link

  • soom

    Re: Windows 8 Metro: Something about application life-cycle


    posted by soom on Apr 04, 2015 10:19

    Blog Comment

     The money saving should be started from early age. At younger age, you are free from the responsibilitiesso you are in a position that you can easily take the risk
  • soom

    Re: Windows 8 Metro: Something about application life-cycle


    posted by soom on Apr 05, 2015 10:54

    I thank you very much for the work you write great articles like this. I hope to see high quality content that is the same from you in the future. I am very confident with creativity and imagination you in writing this website will certainly add a nice…web design colchester

  • brightfuture

    Re: Windows 8 Metro: Something about application life-cycle


    posted by brightfuture on Apr 07, 2015 15:31
    wow, great, I was wondering how to cure acne naturally. and found your site by google, learned a lot, now i’m a bit clear. I’ve bookmark your site and also add rss. keep us updated.karate classes for kids Robina
  • brightfuture

    Re: Windows 8 Metro: Something about application life-cycle


    posted by brightfuture on Apr 08, 2015 07:10
    buy quality backlinks

    It appears as though spent lots of time and effort in your blog. I’ve saved it and i’m searching toward reading through new articles.

     

  • alikhan

    Re: Windows 8 Metro: Something about application life-cycle


    posted by alikhan on Apr 15, 2015 09:28
    This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this.. DoFollow
  • alikhan

    Re: Windows 8 Metro: Something about application life-cycle


    posted by alikhan on Apr 15, 2015 23:25
    Once I thought about things like: why such information is for free here? Because when you write a book then at least on selling a book you get a percentage. Thank you and good luck on informing people more about it…equipogimnasio.com.mx
  • alikhan

    Re: Windows 8 Metro: Something about application life-cycle


    posted by alikhan on Apr 20, 2015 13:14
    I was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject. Bookmarked this page, will come back for more.make money online
  • FaizaKhan

    Re: Windows 8 Metro: Something about application life-cycle


    posted by FaizaKhan on Apr 28, 2015 11:00
    Everything on the globe at the end of the day depends upon comfort. find here
  • BeeOShop

    Re: Windows 8 Metro: Something about application life-cycle


    posted by BeeOShop on Apr 29, 2015 14:40

    Mau info toko tas online di Bandung yang menjual berbagai macam tas untuk keperluan wanita dan anak-anak seperti tas-tas wanita yang branded dari berbagai merek terkenal seperti Louis Vuitton, PradaBrussels, Furla, Chanel, Hermes, dan banyak lagi tas branded wanita lainnya dengan bermacam model seperti dompetslingbaghandbag dan tote bag, yang trendy dengan harga yang terjangkau? Silahkan cek di Bee Bagshop grosir tas online di Bandung yang menjual tas-tas dengan moel dan warna yang bervariasi dengan harga yang murah. Selain tas wanita, kami juga menjual tas sekolah anak model selempang dan ransel yang juga branded tiruan seperti jansport dan kipling dengan banyak variasi model dan warna, dijamin putra-putri anda menyukainya.

    Bagi yang ingin merawat kulit wajah tanpa harus repot dan mahal, simak tips kecantikan berikut yang mudah dan murah. Coba Sabun Amoorea. Manfaat sabun ajaib amoorea ini diantaranya untuk berbagai permasalahan kulit anda, seperti jerawat, scars (bekas jerawat), mengencangkan kulit, membuat kulit tampak lebih cerah dan segar, mengatasi lingkar hitam di bawah mata (mata panda), dll. Untuk melihat review sabun amoorea ini klik di sini. Simak juga testimoni yang sudah menggunakan sabun ini, simak selengkapnya. Meski harga sabun amoorea ini cukup terjangkau, produk ini aman, karena terbuat dari 100% bahan alami dan sudah ada ijin dari BPOM sehingga anda tidak perlu khawatir dan ragu memakainya. Jika aman (tidak berbahaya) apakah memakai sabun amoorea ada efek sampingnya? Reaksi apa yang timbul saat pertama menggunakannya? Simak info lengkapnya di sini.

    How To Get Rid Of Acne and Scars site generally tell about  tips for beauty and health skin, and especially tell anything about acne, myths, acne and scars treatments , not only on your face (including acne and scars on your body such as chest and back)which may help you to war against acne and the scars to leaves on your face and body (back and chest), through naturally, home remedies, and medical treatment. Some people believe that natural treatment is most safe. But its seems would take time longer then medical treatment. In my oppinion, using medical treatment is more effective and you'll see the result faster. To find what the best treatment for your acne, better you understand what causes of acne. The following are some factors which can cause acne: Hormones, diet, stress, medication, clothing, environment factors, genes, and cosmetics. For back or chest acne cases, it may caused by your tight clothes. To get rid of acne on back or chest, it's good to wear synthetic loose clothing, such as cotton linen, to prevent excessive rubbing and irritation on the skin. Another treatment that can help you to get rid of back or chest acne is keep your body always clean, with take a bath regularly, preferably with an anti-bacterial soap or a salicylic acid-based cleanser is highly recommended. When acne goes, it will leaves behind the red on skin, and seems impossible to heal it fast overnight. So, it would be better to do something which may offer some remarkable effects on the redness from acne. If you choose naturally treatment,  just take a cube of ice, garlic, or lemon juice mixed with rose water, choose one of them, then apply to your reddish part of your face for a while. Do this continously and measured, then see the result. Below this, some good habits which may help you to get rid of acne scars naturally and fast are: first, drinking lots of water to makes your skin well hydrated, and finally make you skin regenerate faster.  Second, eat the food that containing much the essential vitamins and mineral to help repairing scars skin from the inside. Third, naturally treatment to get rid of acne scar, by applying aloe vera on scars, may help to avoid more scarring, soothe inflamation, and make your skin keep smooth. Fourth, treat your acne scars with natural ingredient, tomato. Its containing much vitamin A, which very efficient in repairing scars skin.  If you want to get rid of acne scars ons faster than naturally or home remedies treatments, using the latest product of technology, such as laser treatment and chemical peeling, or even you can choose microdermabration that guaranteed more effective than other treatments.

    Ada banyak bermacam permasalahan kulit di wajah, salah satu yang paling menggangu adalah jerawat, apalagi jika yang muncul adalah jerawat batu yang ukurannya besar dan menyebabkan rasa sakit. Solusi mengenai berbagai cara menghilangkan jerawat batu ini banyak sekali ditemukan, mulai dari pengobatan alami, maupun secara medis. Untuk kasus jerawat batu ini, sebaiknya anda bisa mengambil tindakan pengobatan yang tepat, untuk kasus jerawat batu disarankan langsung saja ambil perawatan medis, karena beresiko tinggi meninggalkan bekas berupa bopeng di wajah, jika salah menangani. Dengan langsung mengambil tindakan medis, setidaknya akan meminimalisasi resiko timbulnya scars bopeng di wajah yang mana scars jenis ini relatif sulit dihilangkan. Tidak seperti scars berupa noda/ flek hitam. meski tidak mudah juga, namun berkali-kali lipat jauh lebih mudah dan murah dibandingkan dengan mengatasi bopeng bekas jerawat. Perawatan alami yang dapat anda tempuh untuk mengobati jerawat ataupun scars yang berupa noda hitam/ flek bekas jerawat, anda dapat mencoba dengan menggunakan bahan alami misalnya jeruk nipis atau madu yang sudah sangat terkenal khasiatnya yang untuk kesehatan dan kecantikan kulit. Dengan perawatan alami, cenderung lebih aman, hanya saja untuk perawatan ini biasanya dibutuhkan waktu yang lebih lama serta ketelatenan untuk mengatasinya. FYI, Jeruk nipis ini yang tidak hanya dapat memudarkan flek hitam di wajah, tetapi juga dapat memutihkan dan mencerahkan kulit anda. Namun jika anda tidak memiliki cukup kesabaran, sebaiknya langsung saja konsultasi dengan dokter. Untuk menentukan metode pengobatan jerawat dan scars ini biasanya dokter akan melihat tingkat keparahan dari jerawat/ scars anda, bisa dengan pemberian obat minum seperti anti biotik, obat oles (salep), peeling, mikrodermabrasi, laser atau metode pengobatan lainnya. Namun sebelum anda memutuskan menggunakan salah satu treatment tersebut sebaiknya telah jelas terlebih dahulu mengenai efek samping yang ditimbulkan.

    Seiring dengan semakin tingginya pengguna internet dari waktu ke waktu, hal ini menciptakan peluang bisnis tersendiri. Diataranya peluang bejualan tas murah secara online, buatan konveksi-konveksi lokal. Di Bandung cukup banyak konveksi tas yang membuat beraneka macam tas dan dompet tiruan atau kw. Model-model dari tas wanita ini kebanyakan menjiplak tas dan dompet wanita dari brand terkenal luar negeri seperti merek-merek LV atau Louis Vuitton, Hermes, Chanel, Furla, dll yang sangat terkenal. Tas tiruan seperti ini familiar disebut tas replika/ kw, dengan beraneka tingkatanya: Kw I, Kw II, dll. Tas-tas wanita branded ini di Bee Bagshop dijual dengan harga yang bevariasi antara 66-300 ribuan. Pembelinya berasal dari kalangan anak SMA, anak kuliah, pekerja kantoran, serta ibu-ibu muda. Untuk tas sekolah dan kuliah anak, kebanyakan modelnya meniru model tas branded seperti kipling, dan jansport, dengan model tas punggung/ ransel ataupun model selempang. Untuk harga tas-tas branded kw dijual dengan harga yang jauh di bawah harga aslinya, sehingga bisa dipastikan kualitasnya pun berbeda dengan yang original. Di Bee Bagshop sendiri kisaran harga untuk tas jansport tiruan ini dijual dengan harga 60-80 ribuan, sementara harga barang original mungkin sekitar 800-900 ribuan, bahkan mungkin ada juga yang lebih mahal. Untuk tas ransel branded tiruan ini kebanyakan pembelinya berasal dari anak sekolah dan kuliah.

    Jika anda wanita yang terlalu sibuk bekerja, dan selalu bingung bahkan tidak sempat untuk sekedar memikirkan menu masakan sehari-hari untuk keluarga anda, silahkan kunjungi situs Aneka Resep dan Cara membuat Masakan Praktis Khas Indonesia, situs ini berisi kumpulan resep masakan yang menggunakan bahan-bahan umum seperti ayam, daging sapi, serta beraneka seafood (udang, cumi, ikan), dan juga bahan-bahan makanan yang tidak asing bagi  masyarakat Indonesia seperti tahu, tempe, serta nasi, . Selain itu ada juga resep cemilan khas nusantara, yang dapat anda jadikan inspirasi untuk menu masakan dan makanan ringan keluarga anda di rumah. Seperti resep membuat masakan khas suatu daerah seperti soto ayam lamongan, ataupun masakan khas lebaran seperti opor ayam, beraneka masakan berbahan dasar ayam ataupun bahan makanan lainnya, yang pastinya praktis dan mudah dibuat.

  • wardoyoming

    Re: Windows 8 Metro: Something about application life-cycle


    posted by wardoyoming on May 17, 2015 12:24
    hiningThe Advantage of CNC Metal LathesA CNC Retrofit Is an Econo4 Brass: once t Grosir besi h beam 350 x 350 gunung garuda s (a minimum of 10 5%-11%) Stainless steel does not s toko besi cnp baca selengkapnya elps Push InteroperabilityThings To Consider Before Your Forklift Rental Agper s grosir besi beton polos 10 mm kiloan murah n alloy materials in combination with high carbon conte distributor baja siku 75 x 75 x 9 mm x 6 m terbesar jual besi bajaing A Right Heat Sealer For The JobPhenomenal FRP Struc harga besi wf baja jakarta appy Face1 Sad Face0Viewed 1,038 timesWord count: 718Articla chain Only use the produsen besi plat hitam eser 4 mm per kg
  • wardoyoming

    Re: Windows 8 Metro: Something about application life-cycle


    posted by wardoyoming on May 17, 2015 12:25
    How To Promote Your Music OfflineJazz Guitar Standards - Kenny Burrell Pla kursus website bekasi tempat kursus web murah
  • johnrichard

    Re: Windows 8 Metro: Something about application life-cycle


    posted by johnrichard on May 20, 2015 10:14
    Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle.kettlebell exercises

Add Comment

Login to comment:
  *      *       

From this series