开发者

C# System.InvalidCastException

Why I'm getting this error?

C# System.InvalidCastException

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:

C# System.InvalidCastException

Since WebBrowser is really just a wrapper around IE's ActiveX control, you'll need to be careful about threading issues. I think what you really want to use here is a WebClient and not a WebBrowser, but I'm just guessing about your application.

[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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜