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.
- BackgroundTask = HandlingBgTask.CreateBgTask("_bgTaskName", "BGProcess.BgTask", appTimerTrigger, null);
- if (BackgroundTask == null) return;
- BackgroundTask.Progress += BackgroundTask_Progress;
- 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.
- private async void BackgroundTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) {}
- 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,
- public void Run(IBackgroundTaskInstance taskInstance) {
- taskInstance.Progress = 2; }
Completed event trigger by the BackgroundTaskDeferral class,
- private BackgroundTaskDeferral _deferral;
- _deferral = taskInstance.GetDeferral();
- _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.
- public void Run(IBackgroundTaskInstance taskInstance)
- {
- if (taskInstance == null) return;
- _taskInstance = taskInstance;
- _deferral = taskInstance.GetDeferral();
- _timerPoolTimer = ThreadPoolTimer.CreatePeriodicTimer(TimerPoolCallback, TimeSpan.FromSeconds(2));
- }
- private void TimerPoolCallback(ThreadPoolTimer timer) {
- if ((_cancelRequested == false) && (_progress < 100)) {
- _progress += 1;
- _taskInstance.Progress = _progress;
- } else {
- _deferral.Complete();
- }
- }
Main application
This example uses the SystemTriggerEvent register with TimeZoneChange, whenever TimeZoneChange background task will run,
- IBackgroundTrigger appTimerTrigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false);
- BackgroundTask = HandlingBgTask.CreateBgTask("_bgTaskName", "BGProcess.BgTask", appTimerTrigger, null);
- if (BackgroundTask == null) return;
-
- BackgroundTask.Progress += BackgroundTask_Progress;
- BackgroundTask.Completed += BackgroundTask_Completed;
- private async void BackgroundTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) {
- if (args != null) await UpdateStatus("Background Complted ", 100);
- }
- private async void BackgroundTask_Progress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args) {
- if (args != null) await UpdateStatus("Background Progress ", (int) args.Progress);
- }
- private async Task UpdateStatus(string reportmsg, int percent) {
- await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () f {
- Status.Text = reportmsg;
- pBar.Value = percent;
- }); }
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,
- public void Run(IBackgroundTaskInstance taskInstance) {
- if (taskInstance == null) return;
- _taskInstance = taskInstance;
- _taskInstance.Canceled += TaskInstance_Canceled;
- _deferral = taskInstance.GetDeferral();
- _timerPoolTimer = ThreadPoolTimer.CreatePeriodicTimer(TimerPoolCallback, TimeSpan.FromSeconds(2));
- }
- private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) {
- _cancelRequested = true;
- }