React中的 Scheduler

news2024/10/6 20:30:08

为什么需要调度

在 React 中,组件最终体现为 Fiber,并形成 FiberTree,Fiber 的目的是提高渲染性能,将原先的 React 渲染任务拆分为多个小的微任务,这样做的目的是可以灵活的让出主线程,可以随时打断渲染,后面再继续执行。由于需要让出主线程,需要将任务保存起来,一个个排队执行,需要的时候进行切换,为了实现排队、切换,就需要实现一个调度引擎,哪个任务先执行,哪个任务后执行,暂停之后怎么继续执行。

优先级队列

React 中,Scheduler.js 定义了定义了调度的核心逻辑,Task 包存在一个 PriorityQueue 中,优先级高的任务会先进行处理。

WorkLoop

React 中,WorkLoop 是指循环Fiber Tree 去找需要处理的任务,WorkLoop 分为同步和并发,这两个逻辑几乎一样,并发处理是,要检查是否要暂停并释放主线程给浏览器执行其他任务。

## 同步,不能中断
function workLoopSync() {
  while (workInProgress !== null) {
    performUnitOfWork(workInProgress);
  }
}
function workLoopConcurrent() {
  while (workInProgress !== null && !shouldYield()) {
    performUnitOfWork(workInProgress);
  }
}

shouldYield 大于 5 毫秒就会释放,打开 React Tools Profile 可以看到这个渲染过程

function shouldYieldToHost() {
  const timeElapsed = getCurrentTime() - startTime;
  if (timeElapsed < frameInterval) {
    // The main thread has only been blocked for a really short amount of time;
    // smaller than a single frame. Don't yield yet.
    return false;
  }

在这里插入图片描述

调度

首先,调度创建任务,任务通过 callback function 创建,源码 Sheduler.js -> unstable_scheduleCallback,可以看到,优先级是通过过期时间进行定义的,越早过期的优先级越高,正常的任务 5 秒过期,USER_BLOCKING_PRIORITY_TIMEOUT 阻碍用户操作的任务 250 毫秒。


  var timeout;
  switch (priorityLevel) {
    case ImmediatePriority:
      timeout = IMMEDIATE_PRIORITY_TIMEOUT;
      break;
    case UserBlockingPriority:
      timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
      break;
    case IdlePriority:
      timeout = IDLE_PRIORITY_TIMEOUT;
      break;
    case LowPriority:
      timeout = LOW_PRIORITY_TIMEOUT;
      break;
    case NormalPriority:
    default:
      timeout = NORMAL_PRIORITY_TIMEOUT;
      break;
  }

  var expirationTime = startTime + timeout;

  var newTask = {
    id: taskIdCounter++,
    callback,
    priorityLevel,
    startTime,
    expirationTime,
    sortIndex: -1,
  };

任务加入队列并执行

  if (startTime > currentTime) {
    // This is a delayed task.
    newTask.sortIndex = startTime;
    ##########加入队列
    push(timerQueue, newTask);
    if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
      // All tasks are delayed, and this is the task with the earliest delay.
      if (isHostTimeoutScheduled) {
        // Cancel an existing timeout.
        cancelHostTimeout();
      } else {
        isHostTimeoutScheduled = true;
      }
      // Schedule a timeout.
      requestHostTimeout(handleTimeout, startTime - currentTime);
    }
  } else {
    newTask.sortIndex = expirationTime;
	##########加入队列
    push(taskQueue, newTask);
    if (enableProfiling) {
      markTaskStart(newTask, currentTime);
      newTask.isQueued = true;
    }
    // Schedule a host callback, if needed. If we're already performing work,
    // wait until the next time we yield.
    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }

requestHostCallback 最终会调用 schedulePerformWorkUntilDeadline,schedulePerformWorkUntilDeadline会调用 performWorkUntilDeadline。

### 调用 schedulePerformWorkUntilDeadline
function requestHostCallback(callback) {
  scheduledHostCallback = callback;
  if (!isMessageLoopRunning) {
    isMessageLoopRunning = true;
    schedulePerformWorkUntilDeadline();
  }
}
## 最终调用 performWorkUntilDeadline
let schedulePerformWorkUntilDeadline;
if (typeof localSetImmediate === 'function') {
  // Node.js and old IE.
  // There's a few reasons for why we prefer setImmediate.
  //
  // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
  // (Even though this is a DOM fork of the Scheduler, you could get here
  // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
  // https://github.com/facebook/react/issues/20756
  //
  // But also, it runs earlier which is the semantic we want.
  // If other browsers ever implement it, it's better to use it.
  // Although both of these would be inferior to native scheduling.
  schedulePerformWorkUntilDeadline = () => {
    localSetImmediate(performWorkUntilDeadline);
  };
} else if (typeof MessageChannel !== 'undefined') {
  // DOM and Worker environments.
  // We prefer MessageChannel because of the 4ms setTimeout clamping.
  const channel = new MessageChannel();
  const port = channel.port2;
  channel.port1.onmessage = performWorkUntilDeadline;
  schedulePerformWorkUntilDeadline = () => {
    port.postMessage(null);
  };
} else {
  // We should only fallback here in non-browser environments.
  schedulePerformWorkUntilDeadline = () => {
    localSetTimeout(performWorkUntilDeadline, 0);
  };
}

scheduledHostCallback(hasTimeRemaining, currentTime) ,通过上面的代码的定义可知scheduledHostCallback 就是flushWork,所以这里是调用 flushWork(hasTimeRemaining, currentTime)

const performWorkUntilDeadline = () => {
  if (scheduledHostCallback !== null) {
    const currentTime = getCurrentTime();
    // Keep track of the start time so we can measure how long the main thread
    // has been blocked.
    startTime = currentTime;
    const hasTimeRemaining = true;

    // If a scheduler task throws, exit the current browser task so the
    // error can be observed.
    //
    // Intentionally not using a try-catch, since that makes some debugging
    // techniques harder. Instead, if `scheduledHostCallback` errors, then
    // `hasMoreWork` will remain true, and we'll continue the work loop.
    let hasMoreWork = true;
    try {
      hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
    } finally {
      if (hasMoreWork) {
        // If there's more work, schedule the next message event at the end
        // of the preceding one.
        schedulePerformWorkUntilDeadline();
      } else {
        isMessageLoopRunning = false;
        scheduledHostCallback = null;
      }
    }
  } else {
    isMessageLoopRunning = false;
  }
  // Yielding to the browser will give it a chance to paint, so we can
  // reset this.
  needsPaint = false;
};

flushWork 在调用 workLoop, workLoop 是 scheduler 核心

function flushWork(hasTimeRemaining, initialTime) {
  // 省略一部分代码
  isPerformingWork = true;
  const previousPriorityLevel = currentPriorityLevel;
  try {
    if (enableProfiling) {
      try {
        return workLoop(hasTimeRemaining, initialTime);

workLoop 是 Scheduler 的核心方法,当 currentTask 的 callback 是一个方法,这部分处理暂停任务,如果callback返回一个 function,那么在一次执行中还是执行当前任务,否则任务完成。

 const callback = currentTask.callback;
    if (typeof callback === 'function') {
      currentTask.callback = null;
      currentPriorityLevel = currentTask.priorityLevel;
      const didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
      if (enableProfiling) {
        markTaskRun(currentTask, currentTime);
      }
      const continuationCallback = callback(didUserCallbackTimeout);
      currentTime = getCurrentTime();
      //**************是否是暂停任务
      if (typeof continuationCallback === 'function') {
        currentTask.callback = continuationCallback;
        if (enableProfiling) {
          markTaskYield(currentTask, currentTime);
        }
      } else {
        if (enableProfiling) {
          markTaskCompleted(currentTask, currentTime);
          currentTask.isQueued = false;
        }
        if (currentTask === peek(taskQueue)) {
          pop(taskQueue);
        }
      }
      advanceTimers(currentTime);
    } else {
      pop(taskQueue);
    }

总结

React 调度是用来调度 fiber 任务的,任务可以暂停并将控制权交给浏览器,调度的核心是通过 Priority Queue 实现,根据重要程度进行排序,过期时间作为排序字段,先到期的先执行。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1809408.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

视觉大模型(VLLM)学习笔记

视觉多模态大模型&#xff08;VLLM&#xff09; InternVL 1.5 近日&#xff0c;上海人工智能实验室 OpenGVLab 团队、清华大学、商汤科技合作推出了开源多模态大语言模型项目InternVL 1.5&#xff0c;它不仅挑战了商业模型巨头例如 GPT-4V 的霸主地位&#xff0c;还让我们不禁…

如何一键拷贝PPT中的所有文字?

有时我们可能需要引用PPT的文字&#xff0c;但一个幻灯片一个幻灯片拷贝很是麻烦&#xff0c;我们想一键拷贝PPT中所有幻灯片中的内容&#xff08;最近我就遇到了这个需求&#xff09;。今天就来讲讲这个一键拷贝的技巧。因为大家可能会遇到同样的问题&#xff0c;所以在此记录…

JAVA网络编程,反射及注解知识总结

文章目录 网络编程软件架构三要素IP端口号协议UDP协议发送数据接收数据三种通信方式 TCP协议客户端服务器端三次握手四次挥手 反射获取字节码文件获取构造方法获取成员变量获取成员方法反射的作用 动态代理注解作用格式使用位置注解的原理常见注解元注解自定义注解解析注解 网络…

Elasticsearch index 设置 false,为什么还可以被检索到?

在 Elasticsearch 中&#xff0c;mapping 定义了索引中的字段类型及其处理方式。 近期有球友提问&#xff0c;为什么设置了 index: false 的字段仍能被检索。 本文将详细探讨这个问题&#xff0c;并引入列式存储的概念&#xff0c;帮助大家更好地理解 Elasticsearch 的存储和查…

一文带你轻松掌握Java数组定义和声明

哈喽&#xff0c;各位小伙伴们&#xff0c;你们好呀&#xff0c;我是喵手。运营社区&#xff1a;C站/掘金/腾讯云&#xff1b;欢迎大家常来逛逛 今天我要给大家分享一些自己日常学习到的一些知识点&#xff0c;并以文字的形式跟大家一起交流&#xff0c;互相学习&#xff0c;一…

Android JobService启动系统源码分析

以下就JobService的执行流程,系统层实现进行详解 入口点在JobScheduler.scheduler 系统层JobScheduler是个抽象类,它的实现类是JobScheduler mBinder,一看就知道这里面肯定是跨进程了。它的服务端在JobSchedulerService里面,具体 为什么请看系统服务器启动流程相关文章,…

Python | 正则表达式

?:标记?之前的字符为可选. used&#xff1f; d可有可无 *:匹配>0个重复的在*号之前的字符。 ab*c 匹配多个b &#xff1a;匹配>1个重复的号前的字符。&#xff08;至少一个&#xff09; {n,m}&#xff1a;匹配num个大括号之前的字符或字符集 &#xff08;n < num …

创新案例|创新实时零售模式,千亿时尚巨头Shein的全球扩张之路

SHEIN&#xff0c;一家估值千亿美元的快时尚电商独角兽&#xff0c;是全球增长最快的服饰平台。它通过数据和平台的双轮驱动&#xff0c;构建了全新的“实时零售”模式&#xff0c;实现了数据与商业的紧密衔接。同时&#xff0c;通过领导力和组织能力建设&#xff0c;打造了独特…

实验四、零比特插入《计算机网络》

但凡这句话有一点用的话也不至于一点用都没有。 目录 一、实验目的 二、实验内容 三、实验小结 一、实验目的 掌握零比特插入原理及方法使用任意编程语言实现零比特插入方法。 二、实验内容 掌握零比特插入原理及方法 点对点协议 PPP&#xff08;Point-to-Point Protoco…

LLVM 后端执行流程

异构计算程序工作流程 图4-1中的LLVM后端的主要功能是代码生成&#xff0c;其中包括若干指令生成分析转换pass&#xff0c;将LLVM IR 转换为特定目标架构的机器代码 LLVM 流水线结构 输入指令经过图4-2中的各个阶段&#xff0c;从最初的LLVM IR&#xff0c;逐步演化为Selectio…

市值超越苹果,英伟达的AI崛起与天润融通的数智化转型

Agent&#xff0c;开启客户服务新时代。 世界商业格局又迎来一个历史性时刻。 北京时间6月6日&#xff0c;人工智能芯片巨头英伟达&#xff08;NVDA&#xff09;收涨5.16%&#xff0c;总市值达到3.01万亿美元&#xff0c;正式超越苹果公司&#xff0c;成为仅次于微软&#xf…

UART基本定义、三种编程方式、freertos内怎么用、怎么封装

文章目录 串口基本概念串口的三种编程方式uart编程查询方式不常用、其他两个方式用的多中断方式&#xff1a;代码原理 DMA方式&#xff1a;配置DMA原理代码 效率最高的UART编程方式&#xff1a;是什么&#xff1f;操作 在freertos里面调用uart应该怎么做&#xff1f;代码 面向对…

每日复盘-20240607

今日关注&#xff1a; 这几天市场环境不好&#xff0c;一直空仓。 六日涨幅最大: ------1--------605258--------- 协和电子 五日涨幅最大: ------1--------605258--------- 协和电子 四日涨幅最大: ------1--------605258--------- 协和电子 三日涨幅最大: ------1--------0…

在Linux or Windows中如何优雅的写出对拍

在Linux or Windows中如何优雅的写出对拍 一、前言二、结论1、对拍 三、对拍详解1、什么是对拍呢&#xff1f;&#x1f9d0;2、对拍的组成部分3、输入数据生成4、对拍程序5、操作流程 四、最后 一、前言 网上的对拍程序层出不穷&#xff0c;大多Linux和Windows中的对拍程序都是…

已解决Error || KeyError: ‘The truth value of a Series is ambiguous‘

已解决Error || KeyError: ‘The truth value of a Series is ambiguous’ &#x1f680; 原创作者&#xff1a; 猫头虎 作者微信号&#xff1a; Libin9iOak 作者公众号&#xff1a; 猫头虎技术团队 更新日期&#xff1a; 2024年6月6日 博主猫头虎的技术世界 &#x1f3…

Python 连接 MySQL 及 SQL增删改查(主要使用sqlalchemy)

目录 一、环境 二、MySQL的连接和使用 2.1方式一&#xff1a;sql为主 2.1.1创建连接 2.1.2 表结构 2.1.3 新增数据 ​编辑 2.1.4 查看数据 ​编辑 2.1.5 修改数据 2.1.6 删除数据 2.2方式二&#xff1a;orm对象关系映射 2.2.1 mysql连接 2.2.2 创建表 2.2.3 新增…

已解决Error || IndexError: index 3 is out of bounds for axis 0 with size 3

已解决Error || IndexError: index 3 is out of bounds for axis 0 with size 3 原创作者&#xff1a; 猫头虎 作者微信号&#xff1a; Libin9iOak 作者公众号&#xff1a; 猫头虎技术团队 更新日期&#xff1a; 2024年6月6日 博主猫头虎的技术世界 &#x1f31f; 欢迎来…

【Linux文件篇】优化文件读写,加速数据处理策略——缓冲区

W...Y的主页 &#x1f60a; 代码仓库分享 &#x1f495; 前言&#xff1a;我们已经复习了C语言中的接口&#xff0c;并且学习了许多文件系统调用&#xff0c;了解了文件描述符以及重定向。今天我们继续学习文件缓冲区的相关内容。 缓冲区 在学习C语言时&#xff0c;我们经常…

QSlider样式示例

参考代码&#xff1a; /********************QSlider横向滑动条样式**********************/ QSlider {background-color: rgba(170, 255, 255, 100); /* 设置滑动条主体*/ }QSlider::groove:horizontal {border: 1px solid #999999;height: 8px; /* 默认…

风能远程管理ARMxy嵌入式系统深度解析

智能技术正以前所未有的速度融入传统能源管理体系&#xff0c;而ARMxy工业计算机作为这一变革中的关键技术载体&#xff0c;正以其独特的性能优势&#xff0c;为能源管理的智能化升级铺设道路。本文将聚焦于智能电表、太阳能电站监控、风力发电站远程管理三大应用场景&#xff…