设为首页 加入收藏

TOP

Hangfire源码解析-任务是如何执行的?
2019-09-17 18:34:50 】 浏览:25
Tags:Hangfire 源码 解析 任务 如何 执行

一、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;
        }
        ....省略
    }
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇枚举 下一篇在混合开发框架模式中,简化客户..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目