const int sleep_after_completion = 1; // seconds private async Task ConsumeService() { while (true) { Windows.ApplicationModel.AppService.AppServiceConnection newConnection = new Windows.ApplicationModel.AppService.AppServiceConnection(); #if false newConnection.AppServiceName = "com.microsoft.numbercruncher2"; newConnection.PackageFamilyName = "AppServiceProviderBackgroundApp4-uwp_55b230cc6y9ay"; #else newConnection.AppServiceName = "com.microsoft.numbercruncher"; newConnection.PackageFamilyName = "Microsoft.AppServicesProvider.NumberCruncher_9nthh9tntkkay"; #endif var status = await newConnection.OpenAsync(); if (status != Windows.ApplicationModel.AppService.AppServiceConnectionStatus.Success) { System.Diagnostics.Debug.WriteLine(string.Format("Error {0}", status)); return; } await Task.Delay(sleep_after_connection *1000); var inputs = new Windows.Foundation.Collections.ValueSet(); int min = 0; int max = 100; Random random = new Random(); int val1 = random.Next(min, max); int val2 = random.Next(min, max); System.Diagnostics.Debug.Write(string.Format("{0} + {1} = ", val1, val2)); inputs.Add("value1", val1); inputs.Add("value2", val2); var response = await newConnection.SendMessageAsync(inputs); if (response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success) { var resultText = response.Message["sum"]; System.Diagnostics.Debug.WriteLine(string.Format("{0}", resultText)); CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { textBlock.Text = string.Format("[{3}]: {0} + {1} = {2}", val1, val2, resultText, DateTime.Now.ToString("HH:mm:ss")); }); } else { System.Diagnostics.Debug.WriteLine(string.Format("Error {0}", response.Status)); } await Task.Delay(sleep_after_completion * 1000); } }
private async Task StartMessageAsync(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { Guid?id = null; try { id = (Guid)args.Request.Message[ID_KEY]; if (this.idDirectory.ContainsKey(id.Value)) { throw new Exceptions.PluginException("Start was already send."); } var cancellationTokenSource = new CancellationTokenSource(); this.idDirectory.Add(id.Value, cancellationTokenSource); object output = await PerformStartAsync(sender, args, id, cancellationTokenSource); var outputString = Helper.Serilize(output); var valueSet = new Windows.Foundation.Collections.ValueSet(); valueSet.Add(ID_KEY, id.Value); valueSet.Add(RESULT_KEY, outputString); await args.Request.SendResponseAsync(valueSet); } catch (Exception e) { var valueSet = new ValueSet(); valueSet.Add(ERROR_KEY, e.Message); valueSet.Add(ID_KEY, id.Value); await args.Request.SendResponseAsync(valueSet); } finally { if (id.HasValue) { this.idDirectory.Remove(id.Value); } } }