Hangfire源码解析-任务是如何执行的?

博客介绍了Hangfire任务执行的相关内容。任务创建时,将任务转换为Type存储,参数序列化存储;执行时,根据Type判断是否为静态方法,反序列化参数并使用反射调用方法。还提到从源码中找到‘CoreBackgroundJobPerformer’执行任务的方法。

一、Hangfire任务执行的流程

  1. 任务创建时:
    • 将任务转换为Type并存储(如:HangFireWebTest.TestTask, HangFireWebTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null)
    • 将参数序列化后存储
  2. 任务执行时:
    • 根据Type值判断是否是静态方法,若非静态方法就根据Type从IOC容器中取实例。
    • 反序列化参数
    • 使用反射调用方法:MethodInfo.Invoke

二、Hangfire执行任务

从源码中找到“CoreBackgroundJobPerformer”执行任务的方法

internal class CoreBackgroundJobPerformer : IBackgroundJobPerformer
{
    private readonly JobActivator _activator;   //IOC容器
    ....省略
    
    //执行任务
    public object Perform(PerformContext context)
    {
        //创建一个生命周期
        using (var scope = _activator.BeginScope(
            new JobActivatorContext(context.Connection, context.BackgroundJob, context.CancellationToken)))
        {
            object instance = null;

            if (context.BackgroundJob.Job == null)
            {
                throw new InvalidOperationException("Can't perform a background job with a null job.");
            }
            
            //任务是否为静态方法,若是静态方法需要从IOC容器中取出实例
            if (!context.BackgroundJob.Job.Method.IsStatic)
            {
                instance = scope.Resolve(context.BackgroundJob.Job.Type);

                if (instance == null)
                {
                    throw new InvalidOperationException(
                        $"JobActivator returned NULL instance of the '{context.BackgroundJob.Job.Type}' type.");
                }
            }

            var arguments = SubstituteArguments(context);
            var result = InvokeMethod(context, instance, arguments);

            return result;
        }
    }
    //调用方法
    private static object InvokeMethod(PerformContext context, object instance, object[] arguments)
    {
        try
        {
            var methodInfo = context.BackgroundJob.Job.Method;
            var result = methodInfo.Invoke(instance, arguments);//使用反射调用方法

            ....省略
            
            return result;
        }
        ....省略
    }
}

转载于:https://www.cnblogs.com/yrinleung/p/10552976.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值