public async void Run(IBackgroundTaskInstance taskInstance) { // Ensure our background task remains running taskDeferral = taskInstance.GetDeferral(); // Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage mutex = new Mutex(false, mutexId); // Initialize WeatherShield await shield.BeginAsync(); //Initialise the MCP3008 ADC Chip mcp3008.Initialize(); // Create a timer-initiated ThreadPool task to read data from I2C i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds)); //Create a timer-initiated ThreadPool task to read data from the interrupt handler counting the wind instrument activity windInterruptSample = ThreadPoolTimer.CreatePeriodicTimer(MeasureWindEventData, TimeSpan.FromSeconds(windInterruptSampleInterval)); // Task cancellation handler, release our deferral there taskInstance.Canceled += OnCanceled; //Create the interrupt handler listening to the wind speed pin (13). Triggers the GpioPin.ValueChanged event on that pin //connected to the anemometer. shield.WindSpeedPin.ValueChanged += WindSpeedPin_ValueChanged; //Create the interrupt handler listening to the rain guage pin (26). Triggers the Gpio.ValueChanged event on that pin //connected to the rain guage. shield.RainPin.ValueChanged += RainPin_ValueChanged; }
public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); var updater = new LiveTileScheduler(); await updater.CreateSchedule(); deferral.Complete(); }
public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); try { await Log.InfoAsync("Synchronization background task started"); var authenticatedSilently = await SecurityManager.TryAuthenticateSilently(); if (authenticatedSilently) { IBackendServiceClient storage = new MobileServiceBackendServiceClient(new SyncHandler(), new EventManager(), new LocalSettingsService()); await storage.InitializeAsync(); await storage.TrySyncAsync(); } else { await Log.WarnAsync("Authentication failed."); } await Log.InfoAsync("Synchronization background task completed"); } catch (Exception ex) { await ExceptionHandlingHelper.HandleNonFatalErrorAsync(ex, "Synchronization background task failed.", sendTelemetry: false); } finally { deferral.Complete(); } }
public void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); Initialize(); Start(); }
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { this.SendToForeground(CommunicationConstants.BackgroundTaskStopped); try { ApplicationSettings.BackgroundTaskResumeSongTime.Save(BackgroundMediaPlayer.Current.Position.TotalSeconds); /* //save state ApplicationSettingsHelper.SaveSettingsValue(Constants.CurrentTrack, Playlist.CurrentTrackName); ApplicationSettingsHelper.SaveSettingsValue(Constants.Position, BackgroundMediaPlayer.Current.Position.ToString()); ApplicationSettingsHelper.SaveSettingsValue(Constants.BackgroundTaskState, Constants.BackgroundTaskCancelled); ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState)); backgroundtaskrunning = false; //unsubscribe event handlers systemmediatransportcontrol.ButtonPressed -= systemmediatransportcontrol_ButtonPressed; systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged; Playlist.TrackChanged -= playList_TrackChanged; //clear objects task cancellation can happen uninterrupted playlistManager.ClearPlaylist(); playlistManager = null; */ this.mediaControls.ButtonPressed -= mediaControls_ButtonPressed; playlistManager = null; BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } if (_deferral != null) _deferral.Complete(); }
// Completion groups allow us to immediately take action after a set of downloads completes. // In this sample, the server intentionally replies with an error status for some of the downloads. // Based on the trigger details, we can determine which of the downloads have failed and try them again // using a new completion group. public void Run(IBackgroundTaskInstance taskInstance) { BackgroundTransferCompletionGroupTriggerDetails details = taskInstance.TriggerDetails as BackgroundTransferCompletionGroupTriggerDetails; if (details == null) { // This task was not triggered by a completion group. return; } List<DownloadOperation> failedDownloads = new List<DownloadOperation>(); int succeeded = 0; foreach (DownloadOperation download in details.Downloads) { if (IsFailed(download)) { failedDownloads.Add(download); } else { succeeded++; } } if (failedDownloads.Count > 0) { RetryDownloads(failedDownloads); } InvokeSimpleToast(succeeded, failedDownloads.Count); }
public void Run(IBackgroundTaskInstance taskInstance) { // Connect the Ultrasonic Sensor to digital port 4 IUltrasonicRangerSensor sensor = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin4); // Loop endlessly while (true) { Task.Delay(100).Wait(); //Delay 0.1 second try { // Check the value of the Ultrasonic Sensor string sensorvalue = sensor.MeasureInCentimeters().ToString(); System.Diagnostics.Debug.WriteLine("Ultrasonic reads " + sensorvalue); } catch (Exception ex) { // NOTE: There are frequent exceptions of the following: // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '. // This appears to be caused by the rapid frequency of writes to the GPIO // These are being swallowed here/ // If you want to see the exceptions uncomment the following: // System.Diagnostics.Debug.WriteLine(ex.ToString()); } } }
public void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); InitGPIO(); timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500)); }
public void Run(IBackgroundTaskInstance taskInstance) { // Check the task cost var cost = BackgroundWorkCost.CurrentBackgroundWorkCost; if (cost == BackgroundWorkCostValue.High) { return; } // Get the cancel token var cancel = new System.Threading.CancellationTokenSource(); taskInstance.Canceled += (s, e) => { cancel.Cancel(); cancel.Dispose(); }; // Get deferral var deferral = taskInstance.GetDeferral(); try { // Update Tile with the new xml XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(TileUpdaterTask.w10TileXml); TileNotification tileNotification = new TileNotification(xmldoc); TileUpdater tileUpdator = TileUpdateManager.CreateTileUpdaterForApplication(); tileUpdator.Update(tileNotification); } finally { deferral.Complete(); } }
public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); IReadOnlyList<GeofenceStateChangeReport> reports = GeofenceMonitor.Current.ReadReports(); foreach (var report in reports) { if ((report.NewState != GeofenceState.None) && (report.NewState != GeofenceState.Removed)) { await StatusFile.AddStatusEntry( report.Geofence.Id, report.NewState == GeofenceState.Entered ? EntryType.EnteredZone : EntryType.ExitedZone); } } XmlDocument template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); NotificationTemplateHelper.CompleteToastOrTileTemplate( template, new string[] { "One or more of our fences has been crossed" }, null); ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier(); notifier.Show(new ToastNotification(template)); deferral.Complete(); }
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { _cancelRequested = true; _cancelReason = reason; Debug.WriteLine($"Background '{sender.Task.Name}' Cancel Requested..."); }
/// <remarks> /// If you start any asynchronous methods here, prevent the task /// from closing prematurely by using BackgroundTaskDeferral as /// described in http://aka.ms/backgroundtaskdeferral /// </remarks> public async void Run(IBackgroundTaskInstance taskInstance) { // This deferral should have an instance reference, if it doesn't... the GC will // come some day, see that this method is not active anymore and the local variable // should be removed. Which results in the application being closed. _deferral = taskInstance.GetDeferral(); var restRouteHandler = new RestRouteHandler(); restRouteHandler.RegisterController<AsyncControllerSample>(); restRouteHandler.RegisterController<FromContentControllerSample>(); restRouteHandler.RegisterController<PerCallControllerSample>(); restRouteHandler.RegisterController<SimpleParameterControllerSample>(); restRouteHandler.RegisterController<SingletonControllerSample>(); restRouteHandler.RegisterController<ThrowExceptionControllerSample>(); restRouteHandler.RegisterController<WithResponseContentControllerSample>(); var configuration = new HttpServerConfiguration() .ListenOnPort(8800) .RegisterRoute("api", restRouteHandler) .RegisterRoute(new StaticFileRouteHandler(@"Restup.DemoStaticFiles\Web")) .EnableCors(); // allow cors requests on all origins // .EnableCors(x => x.AddAllowedOrigin("http://specificserver:<listen-port>")); var httpServer = new HttpServer(configuration); _httpServer = httpServer; await httpServer.StartServerAsync(); // Dont release deferral, otherwise app will stop }
public async void Run(IBackgroundTaskInstance taskInstance) { // simple example with a Toast, to enable this go to manifest file // and mark App as TastCapable - it won't work without this // The Task will start but there will be no Toast. //ToastTemplateType toastTemplate = ToastTemplateType.ToastText02; //XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); //XmlNodeList textElements = toastXml.GetElementsByTagName("text"); //textElements[0].AppendChild(toastXml.CreateTextNode("My first Task - Yeah")); //textElements[1].AppendChild(toastXml.CreateTextNode("I'm a message from your background task!")); //ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml)); var deferral = taskInstance.GetDeferral(); RawNotification raw = taskInstance.TriggerDetails as RawNotification; if (raw != null) { Debug.WriteLine( string.Format("XXXXXXXXXXXXXReceived from cloud:XXXXXXXXXX [{0}]", raw.Content)); } deferral.Complete(); }
public async void Run(IBackgroundTaskInstance taskInstance) { // // TODO: Insert code to perform background work // // If you start any asynchronous methods here, prevent the task // from closing prematurely by using BackgroundTaskDeferral as // described in http://aka.ms/backgroundtaskdeferral // var deferral = taskInstance.GetDeferral(); var settings = new I2cConnectionSettings(I2C_ADDRESS); settings.BusSpeed = I2cBusSpeed.FastMode; var aqs = I2cDevice.GetDeviceSelector(); /* Get a selector string that will return all I2C controllers on the system */ var dis = await DeviceInformation.FindAllAsync(aqs); /* Find the I2C bus controller devices with our selector string */ _dht11 = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */ await begin(); while (true) { var temp = await readTemperature(); var hum = await readHumidity(); Debug.WriteLine($"{temp} C & {hum}% humidity"); await Task.Delay(2000); } deferral.Complete(); }
public void Run(IBackgroundTaskInstance taskInstance) { Adapter adapter = null; deferral = taskInstance.GetDeferral(); try { adapter = new Adapter(); dsbBridge = new DsbBridge(adapter); var initResult = dsbBridge.Initialize(); if (initResult != 0) { throw new Exception("DSB Bridge initialization failed!"); } } catch (Exception ex) { if (dsbBridge != null) { dsbBridge.Shutdown(); } if (adapter != null) { adapter.Shutdown(); } throw; } }
public void Run(IBackgroundTaskInstance taskInstance) { var deferal = taskInstance.GetDeferral(); if (taskInstance.TriggerDetails is RawNotification) { var details = taskInstance.TriggerDetails as RawNotification; var arguments = details.Content.Split(':'); if (arguments.Count() > 0) { switch (arguments[0]) { case "new_items": if (arguments.Count() > 1) { XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber); XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge"); badgeElement.SetAttribute("value", arguments[1]); BadgeNotification badge = new BadgeNotification(badgeXml); BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge); } break; } } } deferal.Complete(); }
// // The Run method is the entry point of a background task. // public void Run(IBackgroundTaskInstance taskInstance) { Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting..."); // For performing asynchronous operations in the background task BackgroundTaskDeferral asyncDeferral = taskInstance.GetDeferral(); // // Query BackgroundWorkCost // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount // of work in the background task and return immediately. // var cost = BackgroundWorkCost.CurrentBackgroundWorkCost; var settings = ApplicationData.Current.LocalSettings; settings.Values["BackgroundWorkCost"] = cost.ToString(); // // Associate a cancellation handler with the background task. // taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); // // Get the deferral object from the task instance, and take a reference to the taskInstance; // _deferral = taskInstance.GetDeferral(); _taskInstance = taskInstance; _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1)); asyncDeferral.Complete(); }
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { if (this.deferral != null) { this.deferral.Complete(); } }
public void Run(IBackgroundTaskInstance taskInstance) { try { if (Hub.Instance.VoipTaskInstance != null) { Debug.WriteLine("VoipTask already started."); return; } _deferral = taskInstance.GetDeferral(); Hub.Instance.VoipTaskInstance = this; Debug.WriteLine($"{DateTime.Now} VoipTask started."); taskInstance.Canceled += (s, e) => CloseVoipTask(); } catch (Exception e) { if (Hub.Instance.IsAppInsightsEnabled) { Hub.Instance.RTCStatsManager.TrackException(e); } if (_deferral != null) { _deferral.Complete(); } throw e; } }
public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); taskInstance.Canceled += TaskInstance_Canceled; var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (triggerDetails?.Name != nameof(VoiceCommandService)) return; var connection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); connection.VoiceCommandCompleted += ConnectionOnVoiceCommandCompleted; var command = await connection.GetVoiceCommandAsync(); //even if it's not used, you can run into issues without this line. switch (command.CommandName) { case "ReadTodaysNamedays": await HandleReadNamedaysCommandAsync(connection); break; } deferral.Complete(); }
public async void Run(IBackgroundTaskInstance taskInstance) { // Create the deferral by requesting it from the task instance serviceDeferral = taskInstance.GetDeferral(); AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (triggerDetails != null && triggerDetails.Name.Equals("IMCommandVoice")) { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); // Perform the appropriate command depending on the operation defined in VCD switch (voiceCommand.CommandName) { case "oldback": VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage(); userMessage.DisplayMessage = "The current temperature is 23 degrees"; userMessage.SpokenMessage = "The current temperature is 23 degrees"; VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage, null); await voiceServiceConnection.ReportSuccessAsync(response); break; default: break; } } // Once the asynchronous method(s) are done, close the deferral serviceDeferral.Complete(); }
public void Run(IBackgroundTaskInstance taskInstance) { using (device = new CanvasDevice()) { try { GenerateTileImage(TileTemplateType.TileSquare150x150Image, 150, 150); GenerateTileImage(TileTemplateType.TileWide310x150Image, 310, 150); } catch (Exception e) { if (device.IsDeviceLost(e.HResult)) { // When the device is lost we don't attempt to retry, and instead just wait for // the next time the task runs. return; } // Any other errors we bubble up throw; } } UpdateLiveTiles(); DeleteOldLiveTileImageFiles(); LiveTileUpdater.SetLatestTileImagesInSettings(tiles.Values); }
public async void Run(IBackgroundTaskInstance taskInstance) { //通知 ApplicationDataContainer container = ApplicationData.Current.LocalSettings; bool Update = true; if (container.Values["UpdateCT"]!=null) { Update = (bool)container.Values["UpdateCT"]; } else { container.Values["UpdateCT"] = true; } if (Update) { var deferral = taskInstance.GetDeferral(); await GetLatestNews(); deferral.Complete(); } else { var updater = TileUpdateManager.CreateTileUpdaterForApplication(); updater.Clear(); } }
public void Run(IBackgroundTaskInstance taskInstance) { var backgroundTaskDeferral = taskInstance.GetDeferral(); try { UpdateTile(); } catch (Exception ex) { Debug.WriteLine(ex); } finally { backgroundTaskDeferral.Complete(); } }
/// <summary> /// The entry point of a background task. /// </summary> /// <param name="taskInstance">The current background task instance.</param> public void Run(IBackgroundTaskInstance taskInstance) { Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting..."); // Associate a cancellation handler with the background task. // Even though this task isn't performing much work, it can still be canceled. taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); // Read the sensor readings from the trigger reports SensorDataThresholdTriggerDetails triggerDetails = taskInstance.TriggerDetails as SensorDataThresholdTriggerDetails; // Ensure the type of trigger we are dealing with is of type 'ProximitySensor' if (SensorType.ProximitySensor == triggerDetails.SensorType) { var reports = ProximitySensor.GetReadingsFromTriggerDetails(triggerDetails); var settings = ApplicationData.Current.LocalSettings; var lastReading = reports[reports.Count - 1]; // cache appropriate details from this trigger in application data settings.Values["ReportCount"] = reports.Count.ToString(); settings.Values["LastTimestamp"] = lastReading.Timestamp.ToString("u"); settings.Values["Detected"] = lastReading.IsDetected.ToString(); settings.Values["TaskStatus"] = "Completed at " + DateTime.Now.ToString("u"); } // No deferral is held on taskInstance because we are returning immediately. }
public void Run(IBackgroundTaskInstance taskInstance) { try { var triggerDetail = (AppServiceTriggerDetails) taskInstance.TriggerDetails; _deferral = taskInstance.GetDeferral(); Hub.Instance.ForegroundConnection = triggerDetail.AppServiceConnection; Hub.Instance.ForegroundTask = this; taskInstance.Canceled += (s, e) => Close(); triggerDetail.AppServiceConnection.ServiceClosed += (s, e) => Close(); } catch (System.Exception e) { if (Hub.Instance.IsAppInsightsEnabled) { Hub.Instance.RTCStatsManager.TrackException(e); } if (_deferral != null) { _deferral.Complete(); } throw e; } }
public async void Run(IBackgroundTaskInstance taskInstance) { AddQuestionsResult result = null; BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); #if DEBUG InvokeSimpleToast("Hello from " + taskInstance.Task.Name); #endif try { result = await FeedManager.QueryWebsitesAsync(); #if DEBUG InvokeSimpleToast(String.Format( "There are {0} new questions and {1} updated questions.", result.AddedQuestions, result.UpdatedQuestions)); #endif } catch (Exception ex) { Debug.WriteLine(ex); #if DEBUG InvokeSimpleToast(ex.Message); #endif } deferral.Complete(); }
public async void Run(IBackgroundTaskInstance taskInstance) { taskInstance.Canceled += OnCanceled; var defferal = taskInstance.GetDeferral(); TileHelper.UpdateTile(HomeSensorHelper.GetSensorData()); defferal.Complete(); }
private async void DoBufferWork(IBackgroundTaskInstance taskInstance) { string message = "Hello World!"; string unprotectedMessage = ""; string logFileName = "Bufferlog.txt"; string logFileContent = ""; StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile logFile = await localFolder.CreateFileAsync(logFileName, CreationCollisionOption.OpenIfExists); IBuffer inputBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8); BufferProtectUnprotectResult procBuffer = await DataProtectionManager.ProtectAsync(inputBuffer, m_EnterpriseID); logFileContent += "\r\n" + DateTime.Now + ":" + "ProtStatus:" + procBuffer.ProtectionInfo.Status + "\n"; logFileContent += "\r\n" + "Protected Buffer:" + CryptographicBuffer.EncodeToHexString(procBuffer.Buffer).Substring(0, 5); // If keys are dropped under lock, unprotectBuffer will fail so don't unprotectbuffer under lock if (!m_areKeysDropped) { BufferProtectUnprotectResult unBuffer = await DataProtectionManager.UnprotectAsync(procBuffer.Buffer); unprotectedMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, procBuffer.Buffer); logFileContent += "\n Unprotected string:" + unprotectedMessage; if (message != unprotectedMessage) { throw new Exception("Original string does not match with unprotectedMessage!"); } } await FileIO.AppendTextAsync(logFile, logFileContent); }
public void Run(IBackgroundTaskInstance taskInstance) { var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail; string arguments = details.Argument; var result = details.UserInput; if (arguments == "check") { int sum = int.Parse(result["message"].ToString()); string message = sum == 15 ? "Congratulations, the answer is correct!" : "Sorry, wrong answer!"; string xml = [email protected]"<toast> <visual> <binding template=""ToastGeneric""> <image placement=""appLogoOverride"" src=""Assets/MicrosoftLogo.png"" /> <text>{message}</text> </binding> </visual> </toast>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); ToastNotification notification = new ToastNotification(doc); ToastNotificationManager.CreateToastNotifier().Show(notification); } }