public async Task SetLightsState(LightsStateViewModel lightsState) { if (!_lightSwitchDbService.AnyLightsToSwitchToTargetState(lightsState)) { return; } var transition = GetLightSwitchTransition(lightsState.State); lightsState.State = transition[0]; // trigger light changing on all clients to disable switch _controlHub.Clients.All.SetAllLightsState(lightsState); // save new state to db so new requests fetch updated state var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; var saving = _lightSwitchDbService.SetLightsState(lightsState, cancellationToken); // send request to set lights lightsState.State = transition[1]; var transitionRequestSent = _queueService.SendLightsState(lightsState.LightIds, transition[1]); if (!transitionRequestSent) { // could not send transition request, rollback all actions cancellationTokenSource.Cancel(); } await saving; }