我正在调用一个端点,如果它返回404或在其他异常情况下立即失败,我希望重试该端点。
对于较短的时间跨度工作得很好,但当我使用指数回退运行时,我看到"Scheduling attempt 10/11 in at date“,但没有后续调用。
我想在一个任务中运行它,因为我想让它从主线程中退出队列,并在后台处理它。这个问题可能与正在处理的任务有关吗?
var settingsPage = _contentQueries.GetComponent<SettingsPage>();
var retryCount = 11;
var token = _authorizationService.GetBearerToken();
Task.Factory.StartNew(currentContext => {
HttpContext.Current = (HttpContext) currentContext;
var captureResult = Policy.HandleResult<HttpResponse>(r => r.Status == (int)HttpStatusCode.NotFound).WaitAndRetry(retryCount, retryAttempt =>
{
var nextAttemptInSeconds = Math.Pow(3, retryAttempt);
_logger.Log($"Scheduling retry attempt {retryAttempt}/{retryCount} at {DateTime.Now.AddSeconds(nextAttemptInSeconds)}", activity, Level.Debug);
return TimeSpan.FromSeconds(nextAttemptInSeconds);
}).ExecuteAndCapture(() =>
{
var result = MakeWebClientGetRequest();
if (RemoteErrorOccurred(result))
{
throw new Exception(result.Response);
}
return result;
});
if (captureResult.Outcome == OutcomeType.Successful)
{
_logger.Log("Process successful", activity, Level.Debug);
}
else
{
if (captureResult.FinalException != null)
{
_logger.Log($"Failed to process: {captureResult.FinalException}", activity, Level.Debug);
}
else
{
_logger.Log($"Failed to process after {retryCount} attempts", activity, Level.Debug);
}
}
_databaseFactory.Dispose();
}, HttpContext.Current);private static bool RemoteErrorOccurred(HttpResponse result)
{
return result.Exception != null && result.Status != (int) HttpStatusCode.NotFound;
}发布于 2020-01-09 19:09:00
我最终选择了Hangfire's BackgroundJob.Enqueue而不是Task.Factory.StartNew。应用程序池回收可以防止像我的问题中那样长时间运行的任务。
https://stackoverflow.com/questions/59652947
复制相似问题