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: 

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

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

我通过此测试获得了线程exception:

 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控件的一个包装器,因此您需要注意线程问题。 我认为你真正想要使用的是WebClient而不是WebBrowser,但我只是猜测你的应用程序。

[编辑]

就像@Fun状态一样,你可以只调用GUI线程(假设创建控件的位置。我仍然建议使用WebClient。