简体   繁体   中英

c# InvalidCastException

I try to use this code :

webBrowser.Document.GetElementById("login").SetAttribute("value", "user");

It work great but not when i use it in a new thread. I get an InvalidCastException. What can I do ?

This should work:

delegate void ActionExecutorOnUI(ref HtmlElement a, string b, string c);
private void SetValueOnHtmlElementOnUIThread(this HtmlElement onElement, string propToChange, string valueGiven, WebBrowser linkToWebBrowser)
        {
            if (linkToWebBrowser.InvokeRequired)
            {
                ActionExecutorOnUI d = new ActionExecutorOnUI(SetValueOnHtmlElementOnUIThread);
                linkToWebBrowser.Invoke(d, new object[] { });
            }
            else
                SetValueOnHtmlElementOnUIThread(ref onElement, propToChange, valueGiven);

        }

private void SetValueOnHtmlElementOnUIThread(ref HtmlElement onElement, string propToChange, string valueGiven)
        {
            onElement.SetAttribute("value", "user"); 
        }

webBrowser must be a GUI element, and most GUI elements do not handle multi-threading well. You should typically only access GUI objects on the main UI thread of the application.

The easiest way to delegate calls to the UI thread is to use Dispatcher.Invoke .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM