如何安全地返回已终止的 web worker 的内存?

问题描述 投票:0回答:0

我使用网络工作者上传文件。

它处理小文件。

但是对于大文件,速度变得很慢,我的脚本导致网页崩溃。

它不返回网络工作者的记忆。

见附件

当上传大文件时,Dedicated Workers 不断积累并消耗 GB 内存。

我看到这个警告在网络工作者调用时累积 close()

Scripts may close only the windows that were opened by them.

我将线程数量限制为 5.

我认为web worker的数量不应该超过5个。

class Queue {
    constructor() {
        this.timestamp = new Date().getTime();
        this.activeConnections = {};
        this.threadsQuantity = 5;

    }
    async sendNext() {
        const activeConnections = Object.keys(this.activeConnections).length;
        if (activeConnections >= this.threadsQuantity) {
            return;
        }
        if (!this.chunksQueue.length) {
            if (!activeConnections) {
                this.complete();
            }
            return;
        }
        
        let chunkId = this.chunksQueue.pop();
        this.activeConnections[chunkId] = true;
        this.sendChunk( chunkId) ;
    }
  
    sendChunk( chunkId) {
        if (window.Worker) {
            let chunk = this.getChunk( chunkId)
            const myWorker = new Worker("/assets/js/worker.js?v=" + this.timestamp);
            myWorker.postMessage([this.timestamp, chunkId, chunk]);
            myWorker.onmessage = (e) => {
                var obj = JSON.parse(e.data)
                if( obj.success) {
                    delete this.activeConnections[chunkId];
                    this.sendNext()
                    close();
                } else {
                    sendChunk( chunkId);
                }
            }
        }
    }
}

我尝试了 close() , self.close() 但都得到了相同的警告并且失败了。

我试过 this.close(),但它导致了这个错误。

app.0a4dcc55.js:32 Uncaught TypeError: this.close is not a function
    at _.onmessage 

如何在进程中安全地杀死已终止的网络工作者?

javascript web-worker
© www.soinside.com 2019 - 2024. All rights reserved.