0
在我的網絡工作者,我必須做一個循環處理噸。在C#或Java世界中,我將按如下方式對其進行編碼(Java):在網絡工作者中產生 - setTimeout夠了,還是我必須退出?
// main code:
public static void mainLoop() {
for (Iterator it=getIterator(); it.hasNext() && keepRunning;) {
Object item = it.next();
processThisOne (item);
}
}
// async method
static boolean keepRunning = true;
public static void abort() {
keepRunning = false;
}
以上不適用於web worker。當主循環運行在上面時,後續的postMessage()調用將被處理。
我可以做以下(現爲打字稿):
// kicked off by postMessage event handler
public mainLoop() : void {
if (! keepRunning)
return;
Object item = it.next();
processThisOne (item);
worker.setTimeout(mainLoop, 0);
}
// also callable by postMessage event handler:
static boolean keepRunning = true;
public static void abort() {
keepRunning = false;
}
相反,我可以基本上得到如下?如果是這樣,這是否如此快(setTimeout上的線程之間有任務切換)?
// kicked off by postMessage event handler
public mainLoop() : void {
for (Iterator it=getIterator(); it.hasNext() && keepRunning;) {
Object item = it.next();
processThisOne (item);
// yield
worker.setTimeout(nothing, 0);
}
}
// called by setTimeout:
public static void nothing() {
}
// also callable by postMessage event handler:
static boolean keepRunning = true;
public static void abort() {
keepRunning = false;
}
如果上述工作,然後我的代碼保持簡單。問題是,setTimeout()是否會產生?或者它只是排隊的是呼籲處理後我目前表演結束?
'it'從哪裏獲得物品? – Bergi
所以你想從另一個postMessage處理程序調用'abort()'來攔截「循環」? – Bergi
@Bergi - 不,我只想調用yield來處理一個postMessage,我可以得到另一個。 –