From d49167c72c1a966267ec5ec79003135d04064f88 Mon Sep 17 00:00:00 2001 From: "par.dahlman" Date: Wed, 10 Feb 2016 09:14:05 +0100 Subject: [PATCH] (#36): Guard against KeyNotFound in dictionary This is done since the timer dispatcher may be invoked at the same time as the message is recieved, and then there is a race condition where we might end up with a KeyNotFoundException. --- src/RawRabbit/Operations/Requester.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/RawRabbit/Operations/Requester.cs b/src/RawRabbit/Operations/Requester.cs index 40abd86e..7a53bdb1 100644 --- a/src/RawRabbit/Operations/Requester.cs +++ b/src/RawRabbit/Operations/Requester.cs @@ -75,7 +75,7 @@ public Task RequestAsync(TRequest message, Guid _logger.LogWarning($"Unable to find request timer for {props.CorrelationId}."); } timer?.Dispose(); - responseTcs.TrySetException(new TimeoutException($"The request timed out after {_requestTimeout.ToString("g")}.")); + responseTcs.TrySetException(new TimeoutException($"The request '{props.CorrelationId}' timed out after {_requestTimeout.ToString("g")}.")); }, null, _requestTimeout, new TimeSpan(-1))); consumer.Model.BasicPublish( @@ -143,7 +143,16 @@ private IRawConsumer GetOrCreateConsumerForType(IConsumerConfiguratio { var tcs = tcsAsObj as TaskCompletionSource; _logger.LogDebug($"Recived response with correlationId {args.BasicProperties.CorrelationId}."); - _requestTimerDictionary[args.BasicProperties.CorrelationId]?.Dispose(); + + Timer timer; + if (_requestTimerDictionary.TryRemove(args.BasicProperties.CorrelationId, out timer)) + { + timer?.Dispose(); + } + else + { + _logger.LogInformation($"Unable to find request timer for message {args.BasicProperties.CorrelationId}."); + } _errorStrategy.OnResponseRecievedAsync(args, tcs); if (tcs?.Task?.IsFaulted ?? true) {