当我尝试在backgroundWorker.DoWork函数中使用webBrowser组件时,我遇到了这个例外:
System.InvalidCastException未被用户代码
处理http://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#中使用线程的另一种方式?
因为当我在主要使用Thread.sleep方法时gui冻结!!
答案 0 :(得分:1)
WebBrowser不喜欢从其他线程访问。尝试将其传递给RunWorkerAsync(),如下所示:
{{:key}}
{{:#key}}
{{:#parent.key}}
{{:#parent.parent.key}}
{{:~root.key}}