首页 > 解决方案 > 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(); }));
    }

标签: javascriptc#multithreadingwinforms

解决方案


Javascript 代码在一个线程上运行,所以你不能这样做。相反,您可以使用setIntervalwhich 定期调用如下函数:

<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
    }
}

推荐阅读