在androidwebview中,worker中的postmessage是阻塞调用吗?

but5z9lq  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(255)

我在AndroidWebView中使用worker,当我从worker调用postmessage时,我发现它将阻塞,直到主线程中的worker.onmessage完成。但在chrome桌面上使用相同的代码,它是非阻塞的。
main.js

var worker = new Worker("worker.js");
worker.onmessage = function(e) {
    if (e.data.message == 0) {
        for (var i = 0; i < 10000000; i++) {
            cosine = Math.cos(Math.random());
            if (i % 1000000 == 0) console.log("hello world " + i);
        }
    } else if (e.data.message == 1) {
        console.log("xyz");
    }
};

worker.js

console.log('0')
postMessage({message: 0});
console.log('1')
postMessage({message: 1});
console.log('2')

这些产出是:

2021-07-27 21:58:53.010 2002-2002/com.xxx E/Webview: 0
2021-07-27 21:58:53.011 2002-2002/com.xxx E/Webview: hello world 0
2021-07-27 21:58:53.011 2002-2002/com.xxx E/Webview: hello world 1000000
2021-07-27 21:58:53.068 2002-2002/com.xxx E/Webview: hello world 2000000
2021-07-27 21:58:53.543 2002-2002/com.xxx E/Webview: hello world 3000000
2021-07-27 21:58:53.659 2002-2002/com.xxx E/Webview: hello world 4000000
2021-07-27 21:58:53.915 2002-2002/com.xxx E/Webview: hello world 5000000
2021-07-27 21:58:54.162 2002-2002/com.xxx E/Webview: hello world 6000000
2021-07-27 21:58:54.418 2002-2002/com.xxx E/Webview: hello world 7000000
2021-07-27 21:58:54.667 2002-2002/com.xxx E/Webview: hello world 8000000
2021-07-27 21:58:54.928 2002-2002/com.xxx E/Webview: hello world 9000000
2021-07-27 21:58:55.186 2002-2002/com.xxx E/Webview: 1
2021-07-27 21:58:55.190 2002-2002/com.xxx E/Webview: xyz
2021-07-27 21:58:55.190 2002-2002/com.xxx E/Webview: 2

我希望它打印0、1、2,然后是hello world,然后是xyz。但在主线程中的worker.onmessage完成之前,postmessage似乎将被阻止。虽然通常我们不会在主线程中执行耗时的任务,但我仍然对这种行为感到惊讶。
如果我从主线程调用postmessage,它就不会阻塞。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题