javascript - C# Form WebBrowser 中的 JS UI 卡住了?
问题描述
在 C# Windows Form WebBrowser 中运行 Javacript 代码。需要它能够运行长时间循环而不会卡住表单 UI。有什么想法吗?或者其他方式运行JS来实现这个
代码:
[ComVisible(true)]
public void ExecuteJS(WebBrowser wb)
{
// Create the webpage, testing a long loop to check UI stuck or not
wb.DocumentText = @"<html>
<head>
<title>Test</title>
</head>
<body>
<script>
function TestInvoke() {
while (true) {
window.external.AnotherMethod('Hello');
wait(2500);
}
}
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
</script>
</body>
</html>";
}
}
调用(在一个线程上,它仍然使 UI 卡住):
private void BottingThread()
{
//run the js script
this.Invoke(new Action(() => { webBrowser1.Document.InvokeScript("TestInvoke").ToString(); }));
}
解决方案
Javascript 代码在一个线程上运行,所以你不能这样做。相反,您可以使用setInterval
which 定期调用如下函数:
<script>
function TestInvoke() {
setInterval(function() {
window.external.AnotherMethod('Hello');
}, 2500);
}
</script>
启动/停止逻辑:
setInterval
可以停止使用clearInterval
。将返回您想要停止时setInterval
需要传递的句柄/ID 。clearInterval
两者如何用于启动/停止循环的示例:
var interval = null; // the id of the current loop (initially set to null to indicate that no loop is in progress)
function start() { // the function that starts the loop
if(interval !== null) { // first let's check that there aren't any loops already running
clearInterval(interval); // if so stop them first
}
interval = setInterval(function() { // then start a loop and store its id in interval
// code to be looped
}, 2500); // specify the delay between each iteration
}
function stop() { // the function that stops the loop
if(interval !== null) { // if a loop is in progress
clearInterval(interval); // ... stop it
interval = null; // and set interval to null to indicate that no loop is running
}
}
推荐阅读
- sql-server - Backup\Restore cmd 将数据库从远程服务器复制到桌面
- php - 作曲家下载 mpdf 时的问题
- reactjs - 使用上下文和反应钩子测试组件
- javascript - 图像不会在其父容器之外缩放
- java - 将两个 3 字节整数和一个 2 字节整数组合成一个 8 字节整数
- svg - 无法调整此 svg 文件的大小
- linux - 为什么 bitbake 配方将 do_configure[noexec] 和 do_compile[noexec] 设置为 true?
- python - 将文件写入项目中的特定文件夹
- reactjs - 反应将空对象添加到状态中的对象数组
- c - 在 C 中使用 fscanf 读取文件