Hangfire 中的“作业”字段为 null 或空值

问题描述

在 Startup.cs 中,我尝试将重复性工作加入队列:

RecurringJob.AddOrUpdate(() => Console.WriteLine("test"),Cron.Daily);

但收到错误

enter image description here

请帮助找出我做错了什么。

我的配置:

    //HangFire
    services.AddHangfire(configuration => configuration
      .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
      .UseSimpleAssemblyNameTypeSerializer()
      .UseRecommendedSerializerSettings()
      .UsesqlServerStorage(Configuration.GetConnectionString("HangfireConnection"),new sqlServerStorageOptions
          {
              CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),QueuePollInterval = TimeSpan.Zero,UseRecommendedisolationLevel = true,disableGlobalLocks = true,}
      ));

附言尽管“即发即弃”的工作有效。

解决方法

Hangfire's source 表示当表达式 !recurringJob.ContainsKey("Job") || String.IsNullOrWhiteSpace(recurringJob["Job"]) 为真时抛出。

try
{
    if (!recurringJob.ContainsKey("Job") || String.IsNullOrWhiteSpace(recurringJob["Job"]))
    {
        throw new InvalidOperationException("The 'Job' field has a null or empty value");
    }

    Job = InvocationData.DeserializePayload(recurringJob["Job"]).DeserializeJob();
}
catch (Exception ex)
{
    _errors.Add(ex);
}

recurringJob 字典由 method GetAllEntriesFromHash 设置:

public override Dictionary<string,string> GetAllEntriesFromHash(string key)
{
    if (key == null) throw new ArgumentNullException(nameof(key));

    return _storage.UseConnection(_dedicatedConnection,connection =>
    {
        var result = connection.Query<SqlHash>(
            $"select Field,Value from [{_storage.SchemaName}].Hash with (forceseek,readcommittedlock) where [Key] = @key",new { key },commandTimeout: _storage.CommandTimeout)
            .ToDictionary(x => x.Field,x => x.Value);

        return result.Count != 0 ? result : null;
    });
}

所以可能发生的情况是 GetAllEntriesFromHash 方法返回 null, 或不包含键 Job 的字典(或者它是空/空白)。但是,在 a thread 中,一位 Hangfire 贡献者评论道:

这甚至不是问题,只需忽略这些异常或告诉 Visual Studio 不要破坏它们。 Hangfire 处理大量异常,并可能在关闭期间生成大量 OperationCanceledException,告诉所有后台进程已请求关闭。

因此,这个错误似乎可以忽略。