Background Tasks In Universal Windows Program - Part Eight

Before reading this article, please go through the following articles,

This article explains how to implement the Progress, Canceled, and Completed event.

Progress & Completed

To get status from the background task, the progress and completed events are used. To implement this, the main application has to subscribe to the progress and completed events.

Progress Event: current running status

Completed Event: Background task completes a task, this event gets fired.

Subscribe Event into the Main app

In the main application, once background task has successfully registered, implement the Progress and completed event.

  1. BackgroundTask = HandlingBgTask.CreateBgTask("_bgTaskName""BGProcess.BgTask", appTimerTrigger, null);   
  2. if (BackgroundTask == nullreturn;   
  3. BackgroundTask.Progress += BackgroundTask_Progress;   
  4. BackgroundTask.Completed += BackgroundTask_Completed;   
Note - HandlingBgTask class is a user defined class & it has been implemented in previous articles; this class registers the Background Task.
  1. private async void BackgroundTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) {}  
  2. private async void BackgroundTask_Progress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args) {}  
BackgroundTask changes

Once background task has triggered, run method will be called.

To trigger, the progress and completed event are handled by the IBackgroundTaskInstance.

Value has been assigned to the progress property, event get triggered and this is captured by the main application. If it subscribes,
  1. public void Run(IBackgroundTaskInstance taskInstance) {  
  2.     taskInstance.Progress = 2;  }  
Completed event trigger by the BackgroundTaskDeferral class,
  1. private BackgroundTaskDeferral _deferral;   
  2. _deferral = taskInstance.GetDeferral();   
  3. _deferral.Complete();   
BackgroundTask Progress

We can use the Task or Timer control to run background functionality, in this example I am using the ThreadPoolTimer & this timer will run every 2 seconds and set the progress value & automatically progress the event,  get triggered and handle it in the main application.
  1. public void Run(IBackgroundTaskInstance taskInstance)   
  2. {  
  3.     if (taskInstance == nullreturn;  
  4.     _taskInstance = taskInstance;  
  5.     _deferral = taskInstance.GetDeferral();  
  6.     _timerPoolTimer = ThreadPoolTimer.CreatePeriodicTimer(TimerPoolCallback, TimeSpan.FromSeconds(2));  
  7. }   
  8. private void TimerPoolCallback(ThreadPoolTimer timer) {  
  9.     if ((_cancelRequested == false) && (_progress < 100)) {  
  10.         _progress += 1;  
  11.         _taskInstance.Progress = _progress; // trigger event   
  12.     } else {  
  13.         _deferral.Complete();  
  14.     }  
  15. }  
Main application

This example uses the SystemTriggerEvent register with TimeZoneChange, whenever TimeZoneChange background task will run,
  1. IBackgroundTrigger appTimerTrigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false);  
  2. BackgroundTask = HandlingBgTask.CreateBgTask("_bgTaskName""BGProcess.BgTask", appTimerTrigger, null);  
  3. if (BackgroundTask == nullreturn;  
  4. //Register the Progress and Completed event   
  5. BackgroundTask.Progress += BackgroundTask_Progress;  
  6. BackgroundTask.Completed += BackgroundTask_Completed;  
  7. private async void BackgroundTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) {  
  8.     if (args != null) await UpdateStatus("Background Complted ", 100);  
  9. }  
  10. private async void BackgroundTask_Progress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args) {  
  11.     if (args != null) await UpdateStatus("Background Progress ", (int) args.Progress);  
  12. }   
  13. private async Task UpdateStatus(string reportmsg, int percent) {  
  14.     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () f {  
  15.         Status.Text = reportmsg;  
  16.         pBar.Value = percent;  
  17.     });  }  

Cancel Event

When the progress is on-going, any cancellation request has been raised, it handles it in the Canceled event in the background task. To handle the Cancellation event, set the CancelOnConditionLoss property in BackgroundTaskBuilder class.

When willl Cancel Event raise? Cancellation event is raised based on if the condition fails. Let's see in detail, when creating background task, we can set the condition when the background task should run. While the application is running, if the condition fails, event is canceled and gets triggered. 

The same TimeZoneChange BG adds the condition InternetAvailable. When Timezone is changed if InternetAvailable then BG task will run.

While progress is running disable the internet and canceled event gets triggered,
  1. public void Run(IBackgroundTaskInstance taskInstance) {  
  2.     if (taskInstance == nullreturn;  
  3.     _taskInstance = taskInstance;  
  4.     _taskInstance.Canceled += TaskInstance_Canceled;  
  5.     _deferral = taskInstance.GetDeferral();  
  6.     _timerPoolTimer = ThreadPoolTimer.CreatePeriodicTimer(TimerPoolCallback, TimeSpan.FromSeconds(2));  
  7. }  
  8. private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) {  
  9.     _cancelRequested = true;  
  10. }  


Up Next
    Ebook Download
    View all
    View all