简体   繁体   English

是否可以运行WebAssembly代码异步?

[英]Is it possible to run WebAssembly code async?

I have written a C function that I am able to execute from Angular/TypeScript/JavaScript using WebAssembly: 我编写了一个C函数,我可以使用WebAssembly从Angular / TypeScript / JavaScript执行:

testWebAssembly() {
    Module.ccall("aCFunction", null, [], []); // takes a few seconds to finish
}

This function does some heavy mathematical calculations and needs a few seconds to finish. 这个函数做了一些繁重的数学计算,需要几秒钟才能完成。 It is fired when a user clicks a button: 当用户单击按钮时会触发它:

<button (click)="testWebAssembly()">Launch C function</button>

Is it possible to execute the function so that it does not block the UI of the web application? 是否可以执行该功能,以便它不会阻止Web应用程序的UI?

I tried setTimeOut / async / Promise , but I don't seem to be able to make it work. 我尝试了setTimeOut / async / Promise ,但我似乎无法使其工作。

Thank you! 谢谢!

WebAssembly and JavaScript share the same execution thread, ie when you execute WebAssembly from within JavaScript, your JavaScript code halts, and vice-versa. WebAssembly和JavaScript共享相同的执行线程,即当您从JavaScript中执行WebAssembly时,您的JavaScript代码会停止,反之亦然。 In that respect it's just like executing any other native (ie, browser-supplied) APIs from your JavaScript code. 在这方面,它就像从JavaScript代码执行任何其他本机(即浏览器提供的)API。

One option you do have is to run your WebAssembly in a WebWorker, using postMessage to send messages to your wasm code that executed in a different thread. 您可以选择在WebWorker中运行WebAssembly,使用postMessage将消息发送到在不同线程中执行的wasm代码。 There's a great example here, that renders a fractal using WebWorkers: 这里有一个很好的例子,它使用WebWorkers呈现分形:

https://www.reddit.com/r/rust/comments/8hdq5r/a_rust_javascript_web_workers_fractal_renderer/ https://www.reddit.com/r/rust/comments/8hdq5r/a_rust_javascript_web_workers_fractal_renderer/

In the future WebAssembly will likely have its own support for threading: 将来,WebAssembly可能会有自己的线程支持:

https://github.com/WebAssembly/threads https://github.com/WebAssembly/threads

Asynchronous execution alone won't take it off the main thread. 仅异步执行不会将其从主线程中删除。 What you actually mean is executing it concurrently. 你的意思是同时执行它。 The only way to achieve that on the Web is by using worker threads. 在Web上实现这一点的唯一方法是使用工作线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM