如何从 PerformContext 获得 Hangfire 后台作业的总重试次数?

mso*_*ola 5 c# hangfire

从这篇文章:

如何获取 Hangfire 后台作业的当前尝试次数?

可以使用魔术字符串“RetryCount”获取重试计数。

public void SendEmail(PerformContext context, string emailAddress)
{
   string jobId = context.BackgroundJob.Id;
   int retryCount = context.GetJobParameter<int>("RetryCount");
   // send an email
}
Run Code Online (Sandbox Code Playgroud)

如果我需要获取总重试次数如何?我可以使用类似的东西:

int retries = context.GetJobParameter<int>("Retries");
Run Code Online (Sandbox Code Playgroud)

或者我怎样才能从“PerformContext”中获取该信息(如果可能的话)?

我需要定义的总重试次数,因此我可以在最后一次重试时执行一些任务。

wol*_*yuk 2

如果您使用AutomaticRetryAttribute定义方法的重试尝试次数,则类似以下内容将起作用:

var retryAttempts = context.BackgroundJob.Job.Method.GetCustomAttributes(typeof(AutomaticRetryAttribute), false)
    .Cast<AutomaticRetryAttribute>()
    .Select(a => a.Attempts)
    .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

如果该属性不存在,则将返回0。如果全局设置最大重试次数或稍后在属性中进行修改,这将无济于事。