protected virtual void ManageConsumersLoop(CancellationToken token) { while (!token.IsCancellationRequested) { if (!this._isStopped) { QueueInfo queueInfo = this.CreateQueueInfo(); this._scalingAmount = this._consumerCountManager.GetScalingAmount(queueInfo, this._consumerWorkersCount); int scalingAmount = this._scalingAmount; for (var i = 1; i <= scalingAmount; i++) { this._scalingAmount--; this._consumerWorkersCount++; var thread = new Thread(() => { try { using (IQueueConsumerWorker consumerWorker = this.CreateNewConsumerWorker(token)) { consumerWorker.DoConsume(); } } catch (Exception exception) { System.Diagnostics.Trace.TraceError("DevWeek.Architecture.MessageQueuing.RabbitMQConsumer", exception.ToString(), "QueueName", this.QueueName); } finally { this._consumerWorkersCount--; this._scalingAmount++; } }) { IsBackground = true }; thread.Start(); } } Thread.Sleep(this._consumerCountManager.AutoscaleFrequency); } }
protected async virtual Task ManageConsumersLoopAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { var queueInfo = CreateQueueInfo(); lock (_scalingLock) { _scalingAmount = _consumerCountManager.GetScalingAmount(queueInfo, _consumerWorkersCount); for (var i = 1; i <= _scalingAmount; i++) { Task.Factory.StartNew(async() => { try { Interlocked.Decrement(ref _scalingAmount); Interlocked.Increment(ref _consumerWorkersCount); using (IQueueConsumerWorker consumerWorker = CreateNewConsumerWorker()) { await consumerWorker.DoConsumeAsync(cancellationToken).ConfigureAwait(false); } } catch (Exception exception) { Interlocked.Increment(ref _scalingAmount); Interlocked.Decrement(ref _consumerWorkersCount); _errorLogger?.LogError("RabbitMQ.AdvancedConsumer", exception.ToString(), "QueueName", _queueName); } }, cancellationToken); } } await Task.Delay(_consumerCountManager.AutoscaleFrequency, cancellationToken).ConfigureAwait(false); } }