Worker的创建和销毁耗费性能,发起开发者合理管理已创建的Worker并重复使用。Worker空闲时也会不绝运行,因此当不需要Worker时,可以调用terminate()接口或parentPort.close()方法主动销毁Worker。若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
Worker存在数目限制,支持最多同时存在8个Worker。
在API version 8及之前的版本,当Worker数目超出限制时,会抛出“Too many workers, the number of workers exceeds the maximum.”错误。从API version 9开始,当Worker数目超出限制时,会抛出“Worker initialization failure, the number of workers exceeds the maximum.”错误。
4.示例
DevEco Studio 4.0 Release中,通过File->New->Worker,创建MyWorker
复制代码
完成创建后,wokers目录与pages目录同级,所以后续声明woker时注意路径。
4.1 MyWorker.ts文件
import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';