private async Task PushMessagesAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { var period = TimeSpan.FromSeconds(_random.Next( MIN_PERIOD_IN_SECONDS, MAX_PERIOD_IN_SECONDS)); await Task.Delay(period); if (_eventQueue.Any()) { // Pack events into one message var message = new GatewayMessage { GatewayId = _gatewayId, Events = OptimisticDequeuing(cancellationToken).ToArray() }; NewMessage?.Invoke(this, message); } } }