是否可以异步运行WebAssembly代码? [英] Is it possible to run WebAssembly code async?

查看:73
本文介绍了是否可以异步运行WebAssembly代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个C函数,可以使用WebAssembly从Angular/TypeScript/JavaScript执行:

I have written a C function that I am able to execute from Angular/TypeScript/JavaScript using WebAssembly:

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>

是否可以执行该功能,使其不阻止Web应用程序的UI?

Is it possible to execute the function so that it does not block the UI of the web application?

我尝试了 setTimeOut / async / Promise ,但是我似乎无法使其工作.

I tried setTimeOut/async/Promise, but I don't seem to be able to make it work.

谢谢!

推荐答案

WebAssembly和JavaScript共享同一执行线程,即,当您从JavaScript中执行WebAssembly时,JavaScript代码会暂停,反之亦然.在这方面,这就像从您的JavaScript代码执行其他任何本机(即浏览器提供的)API一样.

WebAssembly and JavaScript share the same execution thread, i.e. when you execute WebAssembly from within JavaScript, your JavaScript code halts, and vice-versa. In that respect it's just like executing any other native (i.e, browser-supplied) APIs from your JavaScript code.

您要做的一个选择是在WebWorker中运行WebAssembly,使用 postMessage 将消息发送到在不同线程中执行的wasm代码.这里有一个很好的例子,它使用WebWorkers渲染了一个分形:

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. There's a great example here, that renders a fractal using WebWorkers:

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

将来,WebAssembly可能会对其线程提供自己的支持:

In the future WebAssembly will likely have its own support for threading:

https://github.com/WebAssembly/threads

这篇关于是否可以异步运行WebAssembly代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆