简体   繁体   English

C#InvalidCastException

[英]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. 我收到一个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. webBrowser必须是GUI元素,并且大多数GUI元素不能很好地处理多线程。 You should typically only access GUI objects on the main UI thread of the application. 通常,您只应在应用程序的主UI线程上访问GUI对象。

The easiest way to delegate calls to the UI thread is to use Dispatcher.Invoke . 将调用委托给UI线程的最简单方法是使用Dispatcher.Invoke

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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