WIN10 development Tutorial How to trigger a background task from a foreground application

Source: Internet
Author: User

This article we mainly talk about the use of background tasks, it is estimated that the big partners will not be unfamiliar, background tasks must be written independently to a runtime component, can not write to the main project code?

Is OK, in the configuration manifest file, you only need to specify the. exe file for executable as the main project in the extension element.

<extension category= "Windows.backgroundtasks" entrypoint= "..."  executable= "Xxxx.exe" >
<BackgroundTasks> ...
</BackgroundTasks>
</Extension>


In fact, executable can be set to $targetnametoken$.exe so that when the application is built, the $targetnametoken$ label is automatically replaced with the actual name of the. exe file.

However, it is very serious not recommended to write background tasks to the main project, a this does not conform to the official documents of the general requirements, not easy Code classification management; Two, this practice will bring serious negative effects, if the background task is active, the foreground application does not run, it does not matter, If the background task execution when the foreground application is running, it is likely to cause the foreground application process restart, to the user's feeling is the flash-back.

 

Good, above just for everyone to popularize common sense, suggest everyone in the work of the best according to the rules, do not always like to engage in those alternative behavior, alternative does not represent innovation, but is naïve. The topic for the

today is: Can I trigger a post-task in the foreground application with the code? We know that the common background tasks have background audio, timer, system events, network Transmission control, and so on triggers, there is no can let us manually to trigger the background task?

has, its name is Applicationtrigger, use it, you can activate the background task at any time in the foreground code, but also can pass the parameter to the background task. When you need to perform background tasks, directly call the Applicationtrigger instance of the Requestasync method can be, if there is no accident (such as debris flow, landslides, earthquakes, etc.), then the background task will be carried out. The


Principle has already been explained to everybody, below still uses the example to speak.

First I define a background task, and you guess what it's for.


Public sealed class bgtask : ibackgroundtask {    public  Async void run (ibackgroundtaskinstance taskinstance)     {   
     var d = taskinstance.getdeferral ();         //  remove data related to triggers          ApplicationTriggerDetails details = taskInstance.TriggerDetails as 
Applicationtriggerdetails;         if  (details != null)          {            //  Take out the parameters passed over             ValueSet ps =  Details.
Arguments;             int na =  Convert.ToInt32 (ps["a"]);             int nb = 
Convert.ToInt32 (ps["B"]);             //  Start the Operation     
        int x = na;
            int res = 0;
            while  (X&NBSP;&LT;=&NBSP;NB)             {      
          res += x;
                x++;                 await  Task.delay  //Delay                 //  Report Progress           
      reportprogress (taskinstance,  (UINT) x,  (UINT) NB);             }              //  Save Calculation Results           
  applicationdata.current.localsettings.values["Result"] = res;
        }         d.complete (); &NBSP;&NBSP;&NBSP;&NBSP}     private void reportprogress (IBackgroundTaskInstance  instance, uint c, uint t)     {              }


The noble character you must have seen, this task is mainly to do addition operations, specify a starting value and a final value, starting from the start value added, has been added to the final value, each plus the operation number +1. Of these, each round of operation will delay 30 milliseconds to facilitate the viewing of progress. This task is not very rigorous, such as it does not detect if the end value is less than the initial value of how to deal with, we know that the line, the old week do not want to complicate the code, only for demonstration.

Then you must remember to refer to the Rutime component project in the main project that has a background task class.

Next, configure the manifest file, open the Package.appxmanifest file, find the application node, note that not the Applications node, no S, and then add the extension point.

<application id= "App" ... >
..... <Extensions>
<extension category= "windows.backgroundtasks" entrypoint= "Backgroundtasks.bgtask" >
<BackgroundTasks>
<task type= "General"/>
</BackgroundTasks>
;/extension>
</Extensions>
</Application>

The


<task type= "General"/> indicates that the post task is generic, generic, a popular background task rather than an elitist background. The

 
manifest file is just a declaration, the background task is not automatically registered, and requires code to complete the registration.


const string task_name =  "Comptask";
private backgroundtaskregistration taskreg = null; Protected override async void onnavigatedto (navigationeventargs e) {   
 var res = await backgroundexecutionmanager.requestaccessasync ();     if  (res == backgroundaccessstatus.unspecified | |  res == backgroundaccessstatus.unspecified)     {         showmessage ("Background task is disabled.)
"); return;     }     taskReg =  BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault (T => t.name == task_name)
 as BackgroundTaskRegistration;     //  Registration Background Tasks     if  (taskreg == null)      {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;BACKGROUNDTASKBUilder bd = new backgroundtaskbuilder ();         //  entry point         bd. Taskentrypoint = typeof (Backgroundtasks.bgtask).
FullName;         //  Task Name &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;BD .
name = task_name;         //  setting triggers         
Applicationtrigger trigger = new applicationtrigger (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;BD.
Settrigger (trigger); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;TASKREG&NBSP;=&NBSP;BD.
Register ();         showmessage ("Background task registration succeeded.)
"); &NBSP;&NBSP;&NBSP;&NBSP}     //  Add event handling     taskreg.progress +
= taskreg_progress;     taskreg.completed += taskreg_compleTed }


You should visit backgroundtaskregistration.alltasks before registering to see if the background task you need is already registered, and duplicate registration is meaningless.

The following code triggers a background task through Applicationtrigger.

    //  remove triggers from registered tasks     applicationtrigger trigger =
 taskReg.Trigger as ApplicationTrigger;
    //  Prepare parameter     valueset p = new valueset ();
    p["a"] = n1;
    p["B"] = n2;     //  triggers background task     var res = await trigger.
Requestasync (P);     switch  (res)     {         case applicationtriggerresult.allowed:              showmessage ("Background task has started.)
");
            break;         case applicationtriggerresult.currentlyrunning:              ShowMessage ("The background task is already running.)
");
            break;         case applicationtriggerresult.disabledbypolicy:              showmessage (the administrator does not allow background tasks.)
");
            break;         case applicationtriggerresult.unknownerror:              showmessage ("An error occurred.")
");
            break; }


When calling the Requestasync method, you can pass the data to the background task, and the data is encapsulated by the Valueset class, which is actually a dictionary model, and key is a string.

The value of the Applicationtriggerresult enumeration is returned after the method call. If the value is allowed indicates that the background task was fired successfully, and if the background task is still running for currentlyrunning, "the number you dialed is on call, please try again later"; If the value is Disabledbypolicy, the background task is disabled.


All ready to see the results of the operation:




Renders the calculated results.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.