ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Windows10 Dev - Background Execution

2020-12-29 07:32:45  阅读:196  来源: 互联网

标签:project task Background Windows10 Dev break background var Execution


The Universal Windows Platform (UWP) introduces new mechanisms, which allow the applications to perform some functionality while the application is not running in the foreground. UWP also increases the ability of the applications to extend their execution time in the background for Background Tasks and Triggers. Background execution is the real complementary tail to the application lifecycle.

Important features of Background Tasks are −

  • A background task is triggered by a system or time event and can be constrained by one or more conditions.

  • When a background task is triggered, its associated handler runs and performs the work of the background task.

  • A background task can run even when the app that registered the background task is suspended.

  • They are part of the standard application platform and essentially provide an app with the ability to register for a system event (trigger). When that event occurs, they run a predefined block of code in the background. System triggers include events such as changes in network connectivity or the system time zone.

  • Background Execution is not guaranteed, so it is not suitable for critical functions and features.

  • The OS has a limitation as to how many background tasks can run at the same time. So even when trigger is fired and conditions are met, the task can still not run.

Create and Register Background Task

Create a background task class and register it to run when your app is not in the foreground. You can run code in the background by writing classes that implement the IBackgroundTask interface. The following sample code shows a very basic starting point for a background task class.

public sealed class MyBackgroundTask : IBackgroundTask { 
   public void Run(IBackgroundTaskInstance taskInstance){ 
      // write code 
   } 
}

You can request access for background task as follows.

var access = await BackgroundExecutionManager.RequestAccessAsync();
 
switch (access) {
 
   case BackgroundAccessStatus.Unspecified: 
      break; 
   case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity: 
      break; 
   case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity: 
      break; 
   case BackgroundAccessStatus.Denied: 
      break; 
   default: 
      break; 
}

To build and register the background task, use the following code.

var task = new BackgroundTaskBuilder {
   Name = "My Task", 
   TaskEntryPoint = typeof(BackgroundStuff.MyBackgroundTask).ToString() 
}; 

var trigger = new ApplicationTrigger(); 
task.SetTrigger(trigger);  
task.Register(); 
 
await trigger.RequestAsync();

Let us understand a simple example of background task by following all the below given steps.

  • Create a new blank UWP project ‘UWPBackgroundDemo’ and add one button in the XAML file.

<Page 
   x:Class = "UWPBackgroundDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPBackgroundDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
      <Button x:Name = "button" Content = "Button" 
         HorizontalAlignment = "Left" Margin = "159,288,0,0" 
         VerticalAlignment = "Top" Click = "button_Click"/> 
   </Grid>
	
</Page>
  • Given below is the button click event implementation in which the background task is registered.

using System; 

using Windows.ApplicationModel.Background; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
 
// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace UWPBackgroundDemo {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary>
	
   public sealed partial class MainPage : Page {

      public MainPage() {
         this.InitializeComponent(); 
      }  
		
      private async void button_Click(object sender, RoutedEventArgs e) {
         var access = await BackgroundExecutionManager.RequestAccessAsync(); 
		 
         switch (access){ 
            case BackgroundAccessStatus.Unspecified: 
               break; 
            case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity: 
               break; 
            case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity: 
               break; 
            case BackgroundAccessStatus.Denied: 
               break; 
            default: 
               break; 
         } 
			
         var task = new BackgroundTaskBuilder {  
            Name = "My Task", 
            TaskEntryPoint = typeof(BackgroundStuff.MyBackgroundTask).ToString() 
         }; 
			
         var trigger = new ApplicationTrigger(); 
         task.SetTrigger(trigger);  
			
         var condition = new SystemCondition(SystemConditionType.InternetAvailable);  
         task.Register(); 
			
         await trigger.RequestAsync(); 
      } 
   } 
}
  • Now create another project, but this time select Windows Runtime Component (Universal Windows) from the menu and give the name Background stuff to this project.

Background stuff

  • Given below is the C# code. which contains MyBackgroundTask class implantation and it will run the background task.

using Windows.ApplicationModel.Background; 
using Windows.UI.Notifications; 
 
namespace BackgroundStuff { 
   public sealed class MyBackgroundTask : IBackgroundTask { 
	
      public void Run(IBackgroundTaskInstance taskInstance) {
         SendToast("Hi this is background Task"); 
      } 
		
      public static void SendToast(string message) { 
         var template = ToastTemplateType.ToastText01; 
         var xml = ToastNotificationManager.GetTemplateContent(template); 
         var elements = xml.GetElementsByTagName("Test"); 
         var text = xml.CreateTextNode(message); 
			
         elements[0].AppendChild(text); 
         var toast = new ToastNotification(xml); 
         ToastNotificationManager.CreateToastNotifier().Show(toast); 
      } 
   } 
}
  • To make this project accessible in the UWPBackgroundDemo project, right click on References > Add References in Solution Explorer and add BackgroundStuff project.

Background stuff Sec

  • Now, let us go to the Package.appxmanifest file of UWPBackgroundDemo project and add the following information in Declarations tab.

Background stuff

  • First build the Background stuff project, then build and execute the UWPBackgroundDemo project.

  • When the above code is compiled and executed, you will see the following window.

Background stuff

  • When you click the button, it will run the background task and will show a notification at the right end of your window.

标签:project,task,Background,Windows10,Dev,break,background,var,Execution
来源: https://www.cnblogs.com/bruce1992/p/14204594.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有