-1

我正在编写一个 Winforms 控件,它包装了一个 JS 库并扩展了一个 Web 浏览器控件。

我这样调用 JavaScript 函数:

    /// <summary>
    /// Asks the browser to run a JavaScript function
    /// </summary>
    /// <param name="name">The name of the JS function. WARNING usually browser JS engines make the first letter of the function lowercase. If you pass 'Foo', the browser will look for 'foo'</param>
    /// <param name="args">The arguments to pass to the method; Should probably be JSON / JSON string.</param>
    /// <returns>The object that the JS function returned</returns>
    private object MyInvokeScript(string name, params object[] args)
    {
        //If we're not on the main thread (the one that owns the control), invoke yourself, in the correct thread.
        if (InvokeRequired)
            return this.Invoke(new ScriptInvokationHandler(MyInvokeScript), new Object[] { name, args });
        else //else, just call the script
            return this.Document.InvokeScript(name, args);
    }

这个方法用来调用我所有公开的方法,根据name参数调用JS函数。

我应该这样做,还是应该期望我的方法的用户在适当的线程上进行调用?

4

1 回答 1

1

如果该方法位于控件内部,则必须始终在 UI 线程上调用它。如果用户想调用任何其他线程,调用它是他的问题,就像每个 WinForms 控件一样。

于 2016-02-18T14:19:41.293 回答