From b9822f22706595de4969621d4e48a6f96179847c Mon Sep 17 00:00:00 2001 From: yhh <359807859@qq.com> Date: Fri, 29 Jan 2021 16:16:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Eworker=E8=BE=85=E5=8A=A9?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/src/ECS/Utils/WorkerUtils.ts | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 source/src/ECS/Utils/WorkerUtils.ts diff --git a/source/src/ECS/Utils/WorkerUtils.ts b/source/src/ECS/Utils/WorkerUtils.ts new file mode 100644 index 00000000..143d0098 --- /dev/null +++ b/source/src/ECS/Utils/WorkerUtils.ts @@ -0,0 +1,45 @@ +module es { + /** + * 开辟一个新线程 + * 注意:它无法获得主线程中的上下文 + */ + export class WorkerUtils { + /** 正在执行的队列 */ + private static readonly pendingJobs = {}; + private static jobIdGen = 0; + + /** + * 创建一个worker + * @param doFunc worker所能做的事情 + * + * @example const worker = es.WorkerUtils.makeWorker(()=>{ + * onmessage = ({data: {jobId, meesage}}) => { + * // worker内做的事 + * console.log('我是线程', message, jobId); + * }; + * }); + * + * worker('主线程发送消息').then(message => { + * console.log('主线程收到消息', message); + * }); + */ + public static makeWorker(doFunc: Function) { + const worker = new Worker(URL.createObjectURL(new Blob([`(${doFunc.toString()})()`]))); + + worker.onmessage = ({ data: { result, jobId } }) => { + if (typeof this.pendingJobs[jobId] == 'function') + this.pendingJobs[jobId](result); + + delete this.pendingJobs[jobId]; + }; + + return (...message: any[]) => { + return new Promise(resolve => { + const jobId = this.jobIdGen++; + this.pendingJobs[jobId] = resolve; + worker.postMessage({ jobId, message }); + }); + } + } + } +} \ No newline at end of file