gpt4 book ai didi

c# - "Specified cast is not valid"错误

转载 作者:行者123 更新时间:2023-11-30 20:06:38 25 4
gpt4 key购买 nike

我正在使用此代码来检查 webBrowser1 中的文本,但我却收到错误“指定的转换无效”。对于 string docText = webBrowser1.Document.Body.InnerText;。任何想法为什么?可能是因为我正在从另一个线程访问 webBrowser 吗?谢谢。

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string docText = webBrowser1.Document.Body.InnerText;

if (docText == "Hello")
{
MessageBox.Show("Alerted!");
}
}

private void timer1_Tick(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}

最佳答案

异常实际上可能是由访问 WebBrowser.Document 引起的属性来自非主 UI 线程的线程。您可以通过在 System.InvalidCastException 的堆栈跟踪中查找以下行来验证这一点:

at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
at System.Windows.Forms.WebBrowser.get_Document()

如果是这种情况,请尝试将网页内容作为参数传递给后台线程:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var docText = (string)e.Argument;
}

private void timer1_Tick(object sender, EventArgs e)
{
var docText = webBrowser1.Document.Body.InnerText;
backgroundWorker1.RunWorkerAsync(docText);
}

关于c# - "Specified cast is not valid"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9566337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com