目前,我有代码,其中 while 循环在 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;
}
因此,为此,我尝试将其替换为 Polly 重试,但使用 Polly 它不会等待并且不会添加日志
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;
}
如果有人可以让我知道,我在代码中做错了什么。真的很有帮助