Reputation: 69
when i trying to use webBrowser component inside the backgroundWorker.DoWork function , i got this exception :
System.InvalidCastException was unhandled by user code
https://i.sstatic.net/EJFT3.jpg
here's my code :
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);
}
or is their another way to use thread in c# ?
cause when i use Thread.sleep method in the main the gui freezes !!
Upvotes: 1
Views: 714
Reputation: 39122
The WebBrowser doesn't like being accessed from other threads. Try passing it in to RunWorkerAsync() like this:
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);
}
Upvotes: 1