C#系统无效例外
为什么我会犯这个错误C#系统无效例外,c#,.net,exception,C#,.net,Exception,为什么我会犯这个错误 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.Wind
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 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();
}
}
例外情况如下所示:
由于WebBrowser实际上只是IE ActiveX控件的包装器,所以您需要小心线程问题。我认为您真正想要使用的是WebClient而不是WebBrowser,但我只是猜测一下您的应用程序
[编辑]
像@Fun states一样,您可以直接调用GUI线程(假设控件就是在那里创建的。我仍然建议使用WebClient。以下内容解决了您的跨线程问题
public delegate string GetStringHandler();
public string GetDocumentText()
{
if (InvokeRequired)
return Invoke(new GetStringHandler(GetDocumentText)) as string;
else
return webBrowser.DocumentText;
}
if (regAddId.IsMatch(GetDocumentText()))
{
}
查看“将异常详细信息复制到剪贴板”的链接?请将结果粘贴到您的问题中。我将启用框架源代码步进和符号服务器。这将使异常显示在抛出它的代码中。uhh…您可以在非GUI线程上访问WebBrowser组件吗?如果您可以粘贴webBrowserMain的值就好了。DocumentTextHaahahahahaha…有人转到这个家伙试图通过自动点击广告来赚钱。