码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-03-18 19:51:26      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:...   info   task   调用   type   text   int   inter   nal   

一、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;
        }
        ....省略
    }
}

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

标签:...   info   task   调用   type   text   int   inter   nal   

原文地址:https://www.cnblogs.com/yrinleung/p/10552976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!