You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中检测代码是否以Hangfire Job运行?

在C#中检测代码是否作为Hangfire Job运行

你可以通过以下几种可靠方式判断代码是否正作为Hangfire Job运行:

  • 使用官方提供的JobCurrent类
    这是Hangfire官方推荐的方式,JobCurrent.Current会在Hangfire执行Job任务时被初始化,非Job环境下返回null:

    using Hangfire;
    
    bool isHangfireJob = JobCurrent.Current != null;
    
  • 通过Job执行上下文判断
    如果你的方法本身是Hangfire Job,可以直接注入JobExecutionContext参数,只要参数能正常获取到,就说明当前处于Job运行环境:

    public void MyHangfireJob(JobExecutionContext context)
    {
        bool isHangfireJob = context != null;
        // 业务逻辑
    }
    

注意:不建议依赖线程上下文的内部标记,这类实现可能随Hangfire版本更新发生变化,优先使用官方公开的API。

内容的提问来源于stack exchange,提问作者honneq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:20:43