我正在编写一个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函数。
我应该这样做,还是我希望我的方法的用户在相应的线程上进行调用?
答案 0 :(得分:1)
如果该方法在控件内部,则必须始终在UI线程上调用它。如果用户想要调用任何其他线程,则调用它是一个问题,就像每个WinForms控件一样。