public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { cancellationTokenSource = new CancellationTokenSource(); Task.Run(() => { try { // Shared code is invoked here var sender = new MobileApp.Services.BackgroundTaskService(); sender.ProcessAsync(cancellationTokenSource.Token).Wait(); } catch (OperationCanceledException) { } finally { if (cancellationTokenSource.IsCancellationRequested) { var message = new CancelledMessage(); Device.BeginInvokeOnMainThread( () => MessagingCenter.Send(message, "CancelledMessage") ); } } }, cancellationTokenSource.Token); return(StartCommandResult.Sticky); }
public async Task Start() { cancellationTokenSource = new CancellationTokenSource(); taskId = UIApplication.SharedApplication.BeginBackgroundTask("LongRunningTask", OnExpiration); try { // Shared code is invoked here var sender = new MobileApp.Services.BackgroundTaskService(); await sender.ProcessAsync(cancellationTokenSource.Token); } catch (OperationCanceledException) { // only used to stop execution } finally { if (cancellationTokenSource.IsCancellationRequested) { var message = new CancelledMessage(); Device.BeginInvokeOnMainThread( () => MessagingCenter.Send(message, "CancelledMessage") ); } } UIApplication.SharedApplication.EndBackgroundTask(taskId); }