C#System.InvalidCastException

时间:2011-03-11 02:18:38

标签: c# .net exception

为什么我收到此错误?

enter image description here

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: 

2 个答案:

答案 0 :(得分:7)

以下解决了您的跨线程问题。

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

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

答案 1 :(得分:0)

我通过此测试获得了一个线程异常:

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();
    }
}

异常如下所示: Exception

由于WebBrowser实际上只是IE的ActiveX控件的包装器,因此您需要注意线程问题。我认为你真正想要使用的是WebClient而不是WebBrowser,但我只是猜测你的应用程序。

<强> [编辑]

与@Fun状态一样,您只需调用GUI线程(假设控件已创建的位置。我仍然建议使用WebClient。