Reputation: 31
Currently, I have the code in which the while loop get's stuck when connection.IsConnected = true
private bool TryConnect()
{
if (!connection.IsConnected)
{
Monitor.Enter(_syncRoot);
try
{
while (!connection.IsConnected)
{
Thread.Sleep(100);
}
}
finally
{
Monitor.Exit(_syncRoot);
}
}
return true;
}
So for this, I have tried replacing this with Polly retry but using Polly it does not wait and the log is not added
private bool TryConnect()
{
if (!connection.IsConnected)
{
Monitor.Enter(_syncRoot);
try
{
var policy = Policy.HandleResult<bool>(r => r == false)
.WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(ex, time) =>
{
Log.LogInformation(
"retry {TimeOut}s");
}
);
policy.Execute(() => connection.IsConnected);
}
finally
{
Monitor.Exit(_syncRoot);
}
}
return true;
}
If someone can let me know, what I am doing wrong with the code. It will be really helpful
Upvotes: 0
Views: 532
Reputation: 22829
From the code that you have posted it is hard to guess which C# driver are you using to connect to RabbitMq. So, I will not able to help you with driver specific code.
But as I can see the connection object's IsConnected
is a property. Which means it is a public surface, which can be used to examine the underlying object's state. In order words it should not cause state change just because you are retrieving the internal state several times.
Your retry logic should focus on the action itself which is responsible to connect to your RabbitMq instance.
retryPolicy.Execute(() => connection.Open());
By the way your code never returns with false
. It's either succeed or fail with some timeout related exception.
Upvotes: 0