I am having a problem with threading from external class. I am quite new in threading so many things still remain mystery to me so keep that in mind.
I did my research and found many topics about it including:
- How to Sleep a thread until callback for asynchronous function is received?
- https://www.youtube.com/watch?v=xaaRBh07N34
And it seems pretty clear but still doesn't help me. Here is my code:
public DownloadContent()
{
adres = @"...";
wb = new WebBrowser();
wb.Navigating += (object sender, WebBrowserNavigatingEventArgs e) => objWait.WaitOne();
wb.DocumentCompleted += (object sender, WebBrowserDocumentCompletedEventArgs e) => objWait.Set(); //Here is the problem
wb.DocumentCompleted += OnDocumentCompleted;
wb.Navigate(adres);
MessageBox.Show("after"); //should print after OnDocumentCompleted
}
private void OnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//some logic
}
Problem is that this WebBrowser class is using separate thread to navigate and complete document. There is nothing wrong with that but I don't know how my main thread is suppose to communicate with it. I was trying to make original thread wait but there is a problem that function that is suppose to start it again objWait.Set() is called by main thread which is currently frozen. I assume that's the real problem. I have tried many strange ways to make it work:
- making another thread for wb.Navigate(...); It didn't work because it cannot work on single thread;
- making separate thread for just objWait.Set(); Didn't work either, not sure why;
- and some even weirder things.
I know it may be trivial for some but I have stuck with it for hours now and I really don't know what to do. So I will be grateful for any help.
*******************************************EDIT*******************************************
Thank you everyone for answers. I see many people have noticed what was my original issue and gave me some advice for which I am grateful, you made my work easier. That being said the nature of this quest was to find out if there is any good way of dealing with it. Anyway thank you for all your advice and directions I will look into them closer once I am finished with this little project (one thing at the time).
I guess I could do just something like that:
public DownloadContent()
{
...
bool flag = true;
wb.DocumentCompleted += OnDocumentCompleted;
wb.DocumentCompleted += (object sender, WebBrowserDocumentCompletedEventArgs e) => flag = false;
wb.Navigate(adres);
while(flag);
MessageBox.Show("after"); //should print after OnDocumentCompleted
}
But I don't know if this is considered valid or elegant solution. I would be grateful for any thoughts on that. Thank you in advance.