在c#中使用web浏览器和线程时,会出现InvalidCastException异常
本文关键字:异常 InvalidCastException 线程 浏览器 web | 更新日期: 2023-09-27 18:02:26
当我试图在backgroundWorker中使用webBrowser组件时。DoWork函数,我得到了这个异常:
系统。InvalidCastException未被用户代码处理
https://i.stack.imgur.com/EJFT3.jpg这是我的代码:
void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
//NOTE : Never play with the UI thread here...
string line;
//time consuming operation
while ((line=sr.ReadLine()) != null ){
int index = line.IndexOf(":");
HtmlDocument doc = web.Document;
Thread.Sleep(1000);
m_oWorker.ReportProgress(cnt);
//If cancel button was pressed while the execution is in progress
//Change the state from cancellation ---> cancel'ed
if (m_oWorker.CancellationPending)
{
e.Cancel = true;
m_oWorker.ReportProgress(0);
return;
}
cnt++;
}
//Report 100% completion on operation completed
m_oWorker.ReportProgress(100);
}
还是c#中使用线程的另一种方式?
原因当我使用线程。睡眠方法在主界面冻结!!
WebBrowser不喜欢被其他线程访问。试着像这样把它传递给RunWorkerAsync():
private void button1_Click(object sender, EventArgs e)
{
HtmlDocument doc = web.Document;
m_oWorker.RunWorkerAsync(doc);
}
void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
HtmlDocument doc = (HtmlDocument)e.Argument;
//NOTE : Never play with the UI thread here...
string line;
//time consuming operation
while ((line = sr.ReadLine()) != null)
{
int index = line.IndexOf(":");
Thread.Sleep(1000);
m_oWorker.ReportProgress(cnt);
//If cancel button was pressed while the execution is in progress
//Change the state from cancellation ---> cancel'ed
if (m_oWorker.CancellationPending)
{
e.Cancel = true;
m_oWorker.ReportProgress(0);
return;
}
cnt++;
}
//Report 100% completion on operation completed
m_oWorker.ReportProgress(100);
}