コード例 #1
0
        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);
        }
コード例 #2
0
        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);
        }