public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundWorkCostValue cost = BackgroundWorkCost.CurrentBackgroundWorkCost; if (cost != BackgroundWorkCostValue.High) { this.deferral = taskInstance.GetDeferral(); if (this.IsBackgroundTestEnable) { await this.StartBackgroundSpeedTest(); this.LoopingUntilTestEndedOrErrorOccur(); this.CreateNotificationWhenTestEnded(); this.InitializeNextTest(); } deferral.Complete(); // Ending background test } else { return; } }
public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundWorkCostValue cost = BackgroundWorkCost.CurrentBackgroundWorkCost; if (cost == BackgroundWorkCostValue.High) { return; } if (taskInstance.TriggerDetails is ApplicationTriggerDetails applicationTriggerDetails) { ValueSet valueSet = applicationTriggerDetails.Arguments; int valueSetCount = valueSet.Count; } using (var cts = new CancellationTokenSource()) { taskInstance.Canceled += (sender, reason) => { cts.Cancel(); }; BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try { await InternalRun(taskInstance, cts.Token); } finally { deferral.Complete(); } } }
/// <summary> /// Work that should be performed from the background agent. /// </summary> /// <returns>Awaitable task is returned.</returns> public async Task TimedBackgroundWorkAsync(BackgroundWorkCostValue cost, CancellationToken ct) { try { // Perform work that needs to be done on a background task/agent... //// Only perform work if user is authenticated //if (Platform.Current.AuthManager.IsAuthenticated() == false) // return Task.CompletedTask; // SAMPLE - Load data from your API, do any background work here. var data = await DataSource.Current.GetQueueItemsAsync(Platform.Current.AuthManager.User?.ID, ct); if (data != null) { var items = data.ToObservableCollection(); if (items.Count > 0) { var index = DateTime.Now.Second % items.Count; Platform.Current.Notifications.DisplayToast(items[index].Item); } } //ct.ThrowIfCancellationRequested(); if (cost <= BackgroundWorkCostValue.Medium) { // Update all voice commands await Platform.Current.ViewModel.UpdateVoiceCommandsAsync(ct); // Load queue data await Platform.Current.ViewModel.QueueViewModel.RefreshAsync(); ct.ThrowIfCancellationRequested(); // Update primary tile await Platform.Current.Notifications.CreateOrUpdateTileAsync(Platform.Current.ViewModel.QueueViewModel); ct.ThrowIfCancellationRequested(); // Update all tiles pinned from this application await Platform.Current.Notifications.UpdateAllSecondaryTilesAsync(ct); } } catch (OperationCanceledException) { throw; } catch (Exception ex) { Platform.Current.Logger.LogErrorFatal(ex, "Failed to complete BackgroundWork from background task due to: {0}", ex.Message); throw ex; } }