Egret 非同步佇列處理
阿新 • • 發佈:2022-03-18
Egret 非同步佇列處理
1.非同步處理器
enum AsyncProcessorEnum { } class AsyncProcessor extends egret.EventDispatcher{ static __pool__ = "AsyncProcessorPool"; public constructor(){ super(); } private m_excuting: boolean = false; private m_processQueue: any[] = []; public addProcess(cb: Function, thisObj?: any, args?: any[], delay?: number) { this.m_processQueue.push([cb, thisObj, args, delay]); } public clearProcess(){ this.m_processQueue = []; } public async excuteProcess(){ if(this.m_excuting) return; this.m_excuting = true; while(this.m_processQueue.length>0) { let cbInfo: any[] = this.m_processQueue.shift(); let cb:Function = cbInfo[0]; let thisObj = cbInfo[1]; let args = cbInfo[2]; let delay = cbInfo[3]; cb.apply(thisObj, args); await new Promise(resolve=>egret.setTimeout(()=>resolve(1),this,delay)); } this.m_excuting = false; this.clearProcess(); } }
2.非同步處理管理器
class GAsyncProcessMgr extends egret.EventDispatcher{ private static _ins:GAsyncProcessMgr; private constructor(){ super(); } public static get ins():GAsyncProcessMgr{ if(!this._ins){ this._ins = new GAsyncProcessMgr(); } return this._ins; } private m_processMap: Object = {}; public addProcess(processId: AsyncProcessorEnum, cb: Function, thisObj?: any, args?: any[], delay?: number) { let processor: AsyncProcessor = this.m_processMap[processId]; if(!processor){ processor = Pool.getItemByClass(AsyncProcessor.__pool__, AsyncProcessor); this.m_processMap[processId] = processor; } processor.addProcess(cb, thisObj, args, delay); } public clearAllProcess(){ for (const processId in this.m_processMap) { if (Object.prototype.hasOwnProperty.call(this.m_processMap, processId)) { this.clearProcess(processId as AsyncProcessorEnum); } } } public clearProcess(processId: AsyncProcessorEnum){ let processor: AsyncProcessor = this.m_processMap[processId]; if(!processor){ return; } processor.clearProcess(); Pool.recover(AsyncProcessor.__pool__, processor); delete this.m_processMap[processId]; } public excuteProcess(processId: AsyncProcessorEnum){ let processor: AsyncProcessor = this.m_processMap[processId]; if(!processor){ return; } processor.excuteProcess(); } }