I'm writing a Winforms Control, that wraps a JS library and extends a web browser control.
I'm calling JavaScript functions like so:
/// <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);
}
This method is used to call all of my publically exposed methods, and calls JS functions based on the name
parameter.
Should I be doing that, or should I expect the user of my methods to do the invokation on the appropriate thread?
If that method is inside a control, it will always have to be called on the UI thread. If the user wants to call it any other thread, it's his problem to invoke it, just like every WinForms control.