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。
- 关于IDisposable的问题
- 为什么我在Visual Studio 2010中找不到或使用UrlEncode?
- Scaffolding EntityFramework 6无法将’System.Data.Entity.Core.Objects.ObjectContext’类型的对象强制转换为’System.Data.Objects.ObjectContext’
- 用户控件的数据源
- 浮点数是什么?
- 使用生成的波形数据在.NET中播放声音
- this.TopMost = true不工作?
- UWP应用程序:无法加载文件或程序集’System.Runtime.WindowsRuntime,Version = 4.0.14.0
- 为什么将dll从GAC复制到project \ bin文件夹