2016-02-18 23 views
-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功能。

我應該這樣做,還是應該期望我的方法的用戶在適當的線程上執行調用?

+0

你認爲你應該做什麼? –

+0

我不應該檢查'Control.InvokeRequired',並立即去'else'語句。 –

回答

1

如果該方法位於控件內部,它總是必須在UI線程上調用。如果用戶想要將其稱爲任何其他線程,那麼調用它就是他的問題,就像每個WinForms控件一樣。

相關問題