Browse Source

feat: 新增各线程controller

es6
iapyang 3 years ago
parent
commit
66e0e4e426
  1. 2
      types/globals.d.ts
  2. 85
      typescript/core/worker/controller/worker.main_thread.controller.ts
  3. 21
      typescript/core/worker/controller/worker.worker_thread.controller.ts

2
types/globals.d.ts vendored

@ -11,3 +11,5 @@ declare const Fix: Obj;
declare interface String {
replaceAll(regx: string, callback: (str: string) => void): string;
}
declare const _global: typeof window;

85
typescript/core/worker/controller/worker.main_thread.controller.ts

@ -0,0 +1,85 @@
import { WorkerChannel } from "../worker.channel";
import type { IWorkerOptions } from "../worker.core";
import WorkerBaseController from "./worker.controller";
export class WorkerMainThreadController extends WorkerBaseController {
/**
* HTML Worker Class
*/
public static hasWorkerClass = !!_global.Worker;
/**
* new Worker, Wroker Class
*/
public canNewWorker: boolean = WorkerMainThreadController.hasWorkerClass;
/**
* 线 new Worker
*/
public timeBeforeNewWorker: number;
/**
* 线 new Worker
*/
public timeAfterNewWorker: number;
public constructor(options: IWorkerOptions) {
super();
if (!this.canNewWorker) {
// 都没有 Worker Class, 没法继续了
return;
}
this.newWorker(options);
}
/**
* Worker 线
*/
public terminate(): void {
this.worker?.terminate();
}
protected reportActionHandlerError(actionType: string, error: any): void {
console.error(`Worker aciton ${actionType}:`, error);
// 主线程的报错, 在 window.onerror 中可以拿到报错堆栈, 直接抛出即可
throw new Error(error);
}
/**
* Worker 线
*/
private newWorker(options: IWorkerOptions) {
this.timeBeforeNewWorker = Date.now();
try {
// 主线程通过 new Worker() 获取 Worker 实例
this.worker = new Worker(options.workerUrl, {
name: options.workerName,
});
/**
* worker
* window.onerror worker.onerror( Worker )
*/
this.worker.onerror = (error): void => {
console.error('Worker onerror:', error);
};
this.timeAfterNewWorker = Date.now();
// 实例化 Channel
this.channel = new WorkerChannel(this.worker, {
actionHandler: this.actionHandler.bind(this),
});
} catch (error) {
console.error('Init worker fail:', error);
// 创建 worker 失败, 标识改为不支持
this.canNewWorker = false;
}
}
}

21
typescript/core/worker/controller/worker.worker_thread.controller.ts

@ -0,0 +1,21 @@
import { WorkerChannel } from "../worker.channel";
import WorkerBaseController from "./worker.controller";
export class WorkerThreadController extends WorkerBaseController {
public constructor() {
super();
// Worker 线程中的全局环境 self 就是 Worker 实例
this.worker = self as any;
this.channel = new WorkerChannel(this.worker, {
actionHandler: this.actionHandler.bind(this),
});
}
protected reportActionHandlerError(actionType: string, error: any): void {
console.error(`Worker aciton ${actionType}:`, error);
// 正常抛出
throw new Error(error);
}
}
Loading…
Cancel
Save