Building Background Tasks for Windows 8 Metro Applications

Just as with traditional Windows apps, you will at times need to perform operations in the background. That is to say operations that need to be performed when your app is not running. Traditionally, you would either create a Windows Service and/or an app that automatically starts upon login. Unfortunately, for Windows 8 Metro Apps it is not possible to do either of these options. However, it does provide support for a new method known as Background Tasks.

Background Tasks for Windows 8 Metro Apps allow you to execute code triggered via one of several triggers, such as Time, Maintenance, Push Notification, etc. In addition, you can also specify one or more Conditions such as Internet Available, User Present, etc. To get started, we first need to create the Background Task itself. Listed below is a simple TimerTask, which implements the IBackgroundTask interface.

 public sealed class TimerTask : IBackgroundTask
 {
 public TimerTask()
 {
 }
 async void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
 {
 taskInstance.Canceled += taskInstance_Canceled;
 //Since the Run method is asnc we need use a deferral
 BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); 
 // put your code with await statements here.
 deferral.Complete(); 
 }
 void taskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
 //Put code here to handle a cancel scenario
 }
 }

This class implements the required Run method for the IBackgroundTask interface as well as a cancelled event handler, which is commonly needed for Background Tasks. You will need to place the code you wish to execute within the Run method as identified. Before your Background Task can be used it must be defined in the Package.appxmanifest included with your project. On the Declarations tab, you will need to add a Background Task. Be sure to check Timer under the Properties area and populate the Entry point with the namespace and class name for the BackgroundTask, such as BackgroundTask.TimerTask. Before the task can be executed, you will need to register it when your application is launched.

 private bool RegisterBackgroundTask()
 {
 BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
 builder.Name = "MyBackgroundTask";
 builder.TaskEntryPoint = "BackgroundTask.TimerTask";
 IBackgroundTrigger trigger = new TimeTrigger(15, false);
 builder.SetTrigger(trigger);
 builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
 IBackgroundTaskRegistration task = builder.Register();
 return true;
 }

This method uses the BackgroundTaskBuilder class to provide details about the task, including the name, entry point, triggers and conditions, etc. IBackgroundTaskRegistration object returned from the Register method can be used to provide feedback from the task such as Progress. Depending upon the purpose for your app, you may choose to register the Background Task when your application launches or after a certain set of conditions or configuration.

Conclusion

While the background task may seem almost like a direct replacement for the traditional Windows Service, unfortunately, this could not be further from the truth. For instance, while you can create a Background Task, which runs every 15 minutes, you are restricted at the amount of processing you can perform. Since Metro apps will often run on battery powered devices they are restricted from using excessive amounts of bandwidth and/or CPU resources. For further information regarding resource constraints and Background Tasks in general, consult the Introduction to Background Tasks document by Microsoft.



Related Articles

Comments

  • Planchas GHD púrpura por un precio barato

    Posted by fqgxuj213 on 07/17/2013 08:06am

    Cabina de pelo, servicio de peluquería y proveedor de cuidado del cabello de alta calidad y marcas de belleza, ofrece ahora la Colección Metallic ghd, una serie de edición limitada de ghd productos en su catálogo exclusivo de estilo produkter.Pladerne de estos alisadores de pelo ghd en la Colección Metallic se suaviza para evitar el bloqueo durante el peinado del cabello. Estas placas también tienen una forma contorneada, como rizos y ondas pueden formarse fácilmente. Además Colección Metallic ghd también viene con un cable giratorio extra-largo, 2,7 metros de altura que permita una mayor libertad en el movimiento, mientras que el peinado del cabello [url=http://ghddescuentosonline.npage.de/]planchas ghd[/url] A planchas ghd es uno de los alisadores de pelo más avanzados tecnológicamente en el mercado, pero eso no quiere decir que es difícil de usar ofertas plancha GHD. Sólo quiere decir que es un muy buen alisadores! Por ejemplo. es una ghd sólo 20 segundos para calentar a la temperatura óptima, y el termostato digital asegura la temperatura se ajusta hasta 5 veces por segundo, por lo que su ghd nunca pierden calor o overopheder.Det significa que una ghd no sólo es fácil de utilizar - sino que también proporciona un resultado perfecto cada vez - incluyendo también a causa de las placas flexibles, asegurando que usted no hace "crack" en el pelo cuando suaviza, rizos o hacer el movimiento en håret.Desuden es una ghd diseñado para ser tan suave como sea posible por el cabello, entre otros utilizando el llamado teknologi.Køber iones negativos que una ghd planchas baratas, usted puede estar seguro de que usted ha hecho una inversión que nunca se arrepentirá. [url=http://ghddescuentosonline.npage.de/]planchas ghd[/url] Vendemos planchas ghd son la principal vendida a la nacionalidad danesa. Dado que las mujeres saben mejor cómo la belleza danesa. Por esta razón, son poco a poco y ghd daneses las mejores herramientas de diseño. Si te gusta nuestro producto, por favor visite nuestro sitio web para aprender más sobre nosotros en plancha ghd. Sorpresa dig.Ønsker esperando que le des a tu cabello un nuevo remedio que? Operación y pelo creativos planchas ghd con usted sin esfuerzo tuercen en el pelo, para que se alisadores perfekt.Ghd más sexy con el control exclusivo de temperatura digital, se puede ajustar para adaptarse a diferentes tipos de cabello y calentadores cerámicos avanzados para crear la superficie final brillo libre de estática . Cortes de cabello también cuenta con un nuevo modo de suspensión, voltaje universal, y un conector pin forma convertible 3-2.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: September 10, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild". This loop of continuous delivery and continuous feedback is …

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds