简体   繁体   English

C#System.InvalidCastException

[英]C# System.InvalidCastException

Why I'm getting this error? 为什么我会收到此错误?

在此处输入图片说明

System.InvalidCastException was unhandled by user code
  Message=Specified cast is not valid.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
       at System.Windows.Forms.WebBrowser.get_Document()
       at System.Windows.Forms.WebBrowser.get_DocumentStream()
       at System.Windows.Forms.WebBrowser.get_DocumentText()
       at SiteBot.MainWindow.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\Documents\Visual Studio 2010\Projects\SiteBot\MainWindow.cs:line 35
       at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
       at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
  InnerException: 

The following solves your cross thread issue. 以下内容解决了您的跨线程问题。

public delegate string GetStringHandler();
public string GetDocumentText()
{
    if (InvokeRequired)
        return Invoke(new GetStringHandler(GetDocumentText)) as string;
    else
        return webBrowser.DocumentText;
}

if (regAddId.IsMatch(GetDocumentText()))
{
}

I get a threading exception with this test: 我在此测试中遇到线程异常:

public class Test
{
    private readonly WebBrowser wb;

    public Test()
    {
        wb = new WebBrowser();
        var bw = new BackgroundWorker();
        bw.DoWork += DoWork;
        bw.RunWorkerAsync();

        while (bw.IsBusy)
        {
            Thread.Sleep(10);
            Application.DoEvents();
        } 
    }

    private void DoWork(object sender, DoWorkEventArgs e)
    {
        wb.Navigate(@"www.clix-cents.com/pages/clickads");
        Thread.Sleep(1000);
        var regex = new Regex("onclick=\\'openad\\(\"([\\d\\w]+\"\\);");
        regex.IsMatch(wb.DocumentText);
    }
}

public class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        new Test();
    }
}

The exception looks like this: 异常如下所示: 例外

Since WebBrowser is really just a wrapper around IE's ActiveX control, you'll need to be careful about threading issues. 由于WebBrowser实际上只是IE的ActiveX控件的包装,因此您需要注意线程问题。 I think what you really want to use here is a WebClient and not a WebBrowser, but I'm just guessing about your application. 我认为您真正想在这里使用的是WebClient,而不是WebBrowser,但我只是在猜测您的应用程序。

[EDIT] [编辑]

Like @Fun states you can just Invoke over to the GUI thread (assuming thats where the control was created. I'd still recommend using a WebClient. 像@Fun状态一样,您可以调用GUI线程(假设多数民众赞成在创建控件的位置。我仍然建议使用WebClient。

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

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