我正在开发一个有角度的应用程序,该应用程序可以创建多个Web工作程序并在工作程序线程中进行单独的工作。我的应用程序通过单击按钮读取文件输入,然后根据文件内提供的[array.length]创建新的Worker。它运作良好。现在,我需要做的是通过单击停止按钮终止所有Web工作者。下面是我两次单击按钮时使用的两种方法。
public i = 0;
public file: any;
public noOfOrders: number;
private worker: Worker;
public uploadDocument(): void {
const fileReader = new FileReader();
fileReader.onload = (e) => {
const k = JSON.parse(fileReader.result.toString());
this.noOfOrders = Math.round(k.orders_per_second / k.credentials.length);
if (typeof Worker !== 'undefined') {
while (this.i < k.credentials.length) {
this.worker = new Worker('./app.worker', { type: 'module' });
this.worker.onmessage = ({ data }) => {
console.log(data + k.credentials.length);
};
this.worker.postMessage({ data: k.credentials[this.i], orders: this.noOfOrders });
this.i++;
}
}
};
fileReader.readAsText(this.file);
}
public stop(): void { // this method only terminates the final worker thread
this.worker.terminate();
}
您每次都覆盖同一个工作程序,这就是为什么您只能终止最后一个工作程序的原因。
相反,将它们存储在一组工作程序中,并在所有工作程序上终止调用。像这样的东西:
public i = 0;
public file: any;
public noOfOrders: number;
private workers: Worker[];
public uploadDocument(): void {
const fileReader = new FileReader();
fileReader.onload = (e) => {
const k = JSON.parse(fileReader.result.toString());
this.noOfOrders = Math.round(k.orders_per_second / k.credentials.length);
if (typeof Worker !== 'undefined') {
while (this.i < k.credentials.length) {
const worker = new Worker('./app.worker', { type: 'module' });
worker.onmessage = ({ data }) => {
console.log(data + k.credentials.length);
};
worker.postMessage({ data: k.credentials[this.i], orders: this.noOfOrders });
this.workers.push(worker);
this.i++;
}
}
};
fileReader.readAsText(this.file);
}
public stop(): void {
this.workers.forEach(w => w.terminate());
}