我正在编写一个 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函数。
我应该这样做,还是应该期望我的方法的用户在适当的线程上进行调用?