private async Task BackgroundTaskAsync() { try { _backgroundService = _backgroundServiceCreationFunc(); await _backgroundService.StartAsync(); _messagingCenter.Send <object, BackgroundServiceState>(this, FromBackgroundMessages.BackgroundServiceState, new BackgroundServiceState(true)); while (!_cancellationTokenSource.IsCancellationRequested) { try { await _backgroundService.PeriodicTaskAsync(); if (!_cancellationTokenSource.IsCancellationRequested) { await Task.Delay(_backgroundService.PeriodicServiceCallInterval, _cancellationTokenSource.Token); } } catch (OperationCanceledException) { } } } catch (Exception e) { Debug.WriteLine(e); } }
/// <summary> /// Start the native background service host /// </summary> public async void Start() { try { if (IsStarted) { return; } IsStarted = true; _cancellationTokenSource = new CancellationTokenSource(); using (var mre = new ManualResetEventSlim()) { await Task.Run(async() => { await StartAsync(); mre.Set(); }, _cancellationTokenSource.Token); if (!mre.Wait(_startupTimeout, _cancellationTokenSource.Token)) { Debug.WriteLine("Startup timed out"); return; } } _messagingCenter.Send <object, BackgroundServiceState>(this, FromBackgroundMessages.BackgroundServiceState, new BackgroundServiceState(true)); } catch (Exception e) { IsStarted = false; Debug.WriteLine(e); } }
private async void Startup() { _starting = true; try { BuildForegroundService(); using (var mre = new ManualResetEventSlim()) { await Task.Run(async() => { await StartInBackground(); mre.Set(); }); if (!mre.Wait(_startupTimeout)) { Log.Error(_builder.ServiceName, "Background service did not cleanup within timeout time"); return; } } IsStarted = true; _messagingCenter.Send <object, BackgroundServiceState>(this, FromBackgroundMessages.BackgroundServiceState, new BackgroundServiceState(true)); _messagingCenter.Subscribe <object, UpdateNotificationMessage>(this, ToBackgroundMessages.UpdateBackgroundServiceNotificationMessage, OnNotificationMessageUpdate); } finally { _starting = false; } }
/// <inheritdoc /> /// Note that the system calls this on your service's main thread. /// A service's main thread is the same thread where UI operations take place for Activities running in the same process. /// You should always avoid stalling the main thread's event loop. /// When doing long-running operations, network calls, or heavy disk I/O, you should kick off a new thread, or use AsyncTask`3. public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { var stopRequest = intent.GetBooleanExtra(StopServiceExtra, false); if (!stopRequest && (IsStarted || _starting)) // Not a stop request, already started or starting { return(StartCommandResult.Sticky); } Task.Factory.StartNew(async() => { if (!stopRequest) // Start request { _starting = true; BuildForegroundService(); await StartInBackground(); _starting = false; IsStarted = true; _messagingCenter.Send <object, BackgroundServiceState>(this, FromBackgroundMessages.BackgroundServiceState, new BackgroundServiceState(true)); _messagingCenter.Subscribe <object, UpdateNotificationMessage>(this, ToBackgroundMessages.UpdateBackgroundServiceNotificationMessage, OnNotificationMessageUpdate); } else // Stop request { await Cleanup(); } }); return(StartCommandResult.Sticky); }
private void ConfigureHub() { _hubConnection = new HubConnectionBuilder() .WithUrl($"{App.AzureBackendUrl}/api/gamehub") .Build(); _hubConnection.KeepAliveInterval = new TimeSpan(0, 0, 5); _hubConnection.Closed += async(error) => { try { SetIsReconnecting(true); await UserDialogs.Instance.AlertAsync("Hub Connection closed. Will try to reconnect...", "Hub Connection", "Ok"); //ry to reconnect await Task.Delay(new Random().Next(0, 5) * 1000); await StartHubAsync(); } catch (Exception ex) { await UserDialogs.Instance.AlertAsync($"trying to reconnect - connection.StartAsync(): {ex.Message}", "Hub Connection", "Ok"); } finally { SetIsReconnecting(false); } }; _hubConnection.On(nameof(IGameHub.GameCreated), () => { _messagingCenter.Send(this, nameof(GameCreatedMessage), new GameCreatedMessage()); }); _hubConnection.On <Guid>(nameof(IGameHub.PlayerJoinedGame), (gameId) => { _messagingCenter.Send(this, nameof(PlayerJoinedGameMessage), new PlayerJoinedGameMessage(gameId)); }); _hubConnection.On <Guid>(nameof(IGameHub.MovementMade), (gameId) => { _messagingCenter.Send(this, nameof(MovementMadeMessage), new MovementMadeMessage(gameId)); }); _hubConnection.On <Guid>(nameof(IGameHub.GameFinished), (gameId) => { _messagingCenter.Send(this, nameof(GameFinishedMessage), new GameFinishedMessage(gameId)); }); }
protected override async Task OnInternalAppearingAsync() { try { await ViewModelStateItem.RunActionAsync(async() => { await RefreshData(); }, () => SetLabelsStateItem(openmediavault.UpdateManagement, openmediavault.Loading_PleaseWait___), () => { SetLabelsStateItem(openmediavault.UpdateManagement, openmediavault.Done___); }); } catch (AuthorizationException ex) { if (!retry) { SetLabelsStateItem(openmediavault.Error, ex.Message); _messagingCenter.Send("this", MessengerKeys.SessionExpired, "item"); } else { retry = false; await Task.Delay(100); await OnInternalAppearingAsync(); } } catch (Exception e) { SetLabelsStateItem(openmediavault.Error, e.Message); } await base.OnInternalAppearingAsync(); retry = true; }
private async Task ExecuteDeleteCommand() { if (!await _dialog.DisplayAlertAsync($"Delete {AlterEgo}", "Are you sure?", "Cancel", "OK")) { return; } IsBusy = true; try { var status = await _client.DeleteAsync($"superheroes/{Id}"); if (status != HttpStatusCode.NoContent) { await _dialog.DisplayAlertAsync("Error", $"Error from api: {status}", "OK"); } else { _messaging.Send(this, DeleteSuperhero, Id); await _navigation.BackAsync(); } } catch (Exception e) { await _dialog.DisplayAlertAsync(e); } IsBusy = false; }
public void OnBackButtonPressed() { if (SelectedContact.Favorite) { _messagingCenter.Send(this, "ClearFavorites", SelectedContact); } }
private async Task ExecuteSaveCommand() { IsBusy = true; var powers = Powers?.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()) ?? new string[0]; var superhero = new SuperheroUpdateDTO { Id = Id, Name = Name, AlterEgo = AlterEgo, Occupation = Occupation, CityName = CityName, PortraitUrl = PortraitUrl, BackgroundUrl = BackgroundUrl, FirstAppearance = FirstAppearance, Gender = Gender, Powers = new HashSet <string>(powers) }; try { var status = await _client.PutAsync($"superheroes/{Id}", superhero); if (status != HttpStatusCode.NoContent) { await _dialog.DisplayAlertAsync("Error", $"Error from api: {status}", "OK"); } else { var superheroDetailsDTO = new SuperheroDetailsDTO { Id = Id, Name = Name, AlterEgo = AlterEgo, Occupation = Occupation, CityName = CityName, PortraitUrl = PortraitUrl, BackgroundUrl = BackgroundUrl, FirstAppearance = FirstAppearance, Gender = Gender, Powers = superhero.Powers }; _messaging.Send(this, UpdateSuperhero, superheroDetailsDTO); await _navigation.CancelAsync(); } } catch (Exception e) { await _dialog.DisplayAlertAsync(e); } IsBusy = false; }
private async Task ExecuteSaveCommand() { IsBusy = true; var powers = Powers?.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()) ?? new string[0]; var superhero = new SuperheroCreateDTO { Name = Name, AlterEgo = AlterEgo, Occupation = Occupation, CityName = CityName, PortraitUrl = PortraitUrl, BackgroundUrl = BackgroundUrl, FirstAppearance = FirstAppearance, Gender = Gender, Powers = new HashSet <string>(powers) }; try { var(status, uri) = await _client.PostAsync("superheroes", superhero); if (status != HttpStatusCode.Created) { await _dialog.DisplayAlertAsync("Error", $"Error from api: {status}", "OK"); } else { var id = int.Parse(uri.AbsoluteUri.Substring(uri.AbsoluteUri.LastIndexOf("/") + 1)); var superheroListDTO = new SuperheroListDTO { Id = id, Name = Name, AlterEgo = AlterEgo, PortraitUrl = PortraitUrl }; _messaging.Send(this, AddSuperhero, superheroListDTO); await _navigation.CancelAsync(); } } catch (Exception e) { await _dialog.DisplayAlertAsync(e); } IsBusy = false; }
private async Task ExecuteDeleteCommand() { // TODO: Implement confirm dialog IsBusy = true; await _client.DeleteAsync($"superheroes/{Id}"); _messaging.Send(this, DeleteSuperhero, Id); await _navigation.BackAsync(); IsBusy = false; }
/// <summary> /// Sysop Command to enable a disabled module from the module configuration (Enabled: 0) /// /// Syntax: /SYS ENABLE MODULEID /// </summary> /// <param name="commandSequence"></param> private void ModuleEnable(IReadOnlyList <string> commandSequence) { if (commandSequence.Count < 3) { _sessions[_channelNumber].SendToClient("\r\n|RESET||WHITE||B|Invalid Command -- Syntax: /SYS ENABLE <MODULEID>|RESET|\r\n".EncodeToANSIString()); return; } var moduleChange = commandSequence[2].ToUpper(); if (!_modules.ContainsKey(moduleChange)) { _sessions[_channelNumber].SendToClient("\r\n|RESET||WHITE||B|Invalid Module -- Syntax: /SYS ENABLE <MODULEID>|RESET|\r\n".EncodeToANSIString()); return; } if ((bool)_modules[moduleChange].ModuleConfig.ModuleEnabled) { _sessions[_channelNumber].SendToClient($"\r\n|RESET||WHITE||B|{_modules[moduleChange].ModuleIdentifier} already enabled -- Syntax: /SYS ENABLE <MODULEID>|RESET|\r\n".EncodeToANSIString()); return; } _messagingCenter.Send(this, EnumMessageEvent.EnableModule, _modules[moduleChange].ModuleIdentifier); }
private async Task ExecuteSaveCommand() { IsBusy = true; var powers = Powers?.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()) ?? new string[0]; var superhero = new SuperheroUpdateDTO { Id = Id, Name = Name, AlterEgo = AlterEgo, Occupation = Occupation, CityName = CityName, PortraitUrl = PortraitUrl, BackgroundUrl = BackgroundUrl, FirstAppearance = FirstAppearance, Gender = Gender, Powers = new HashSet <string>(powers) }; await _client.PutAsync($"superheroes/{Id}", superhero); var superheroDetailsDTO = new SuperheroDetailsDTO { Id = Id, Name = Name, AlterEgo = AlterEgo, Occupation = Occupation, CityName = CityName, PortraitUrl = PortraitUrl, BackgroundUrl = BackgroundUrl, FirstAppearance = FirstAppearance, Gender = Gender, Powers = superhero.Powers }; _messaging.Send(this, UpdateSuperhero, superheroDetailsDTO); await _navigation.CancelAsync(); IsBusy = false; }
private async Task ExecuteSaveCommand() { IsBusy = true; var powers = Powers?.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()) ?? new string[0]; var superhero = new SuperheroCreateDTO { Name = Name, AlterEgo = AlterEgo, Occupation = Occupation, CityName = CityName, PortraitUrl = PortraitUrl, BackgroundUrl = BackgroundUrl, FirstAppearance = FirstAppearance, Gender = Gender, Powers = new HashSet <string>(powers) }; var uri = await _client.PostAsync("superheroes", superhero); var id = int.Parse(uri.AbsoluteUri.Substring(uri.AbsoluteUri.LastIndexOf("/") + 1)); var superheroListDTO = new SuperheroListDTO { Id = id, Name = Name, AlterEgo = AlterEgo, PortraitUrl = PortraitUrl }; _messaging.Send(this, AddSuperhero, superheroListDTO); await _navigation.CancelAsync(); IsBusy = false; }
public void Publish <T>(T args) { _messagingCenter.Send <IMessageBus, T>(this, typeof(T).Name, args); }
public void DoAThing() { _messagingCenter.Send(this, "test"); }
private void OnGetBackgroundServiceState(object obj) { var msg = new BackgroundServiceState(BackgroundService != null && BackgroundService.IsStarted); _messagingCenter.Send <object, BackgroundServiceState>(this, FromBackgroundMessages.BackgroundServiceState, msg); }
public void Send <T>(T message) { messagingCenter.Send(this, nameof(T), message); }