My VB.NET (WPF) application has drop-down lists with names of states and their cities. I use a loop to iterate through a selected state and its cities and I perform some functions regarding the cities. I check N number of webpages for every city in the loop and populate a Datagrid with some results using a BackGroundWorker.
However, since I am using a backgroundworker in the loop, it is executed and sent to the background and the code keeps moving forward. I need the code to wait until backgroundworker (RunWorkerAsync) is finished to move onto the next line. It works perfectly when I use it for one city, but when I use it in a loop for a list of cities, it just keeps executing the next lines after backgroundworker and the loop keeps going on.
I have researched this before and the only option that the solutions gave me was to introduce a RunWorkerCompleted in the code. That would mean that I will have to split my code in two parts and place the stuff I want to be executed afterward in the RunWorkerCompleted. Would that work in a loop? Here's some PseudoCode:
For i as integer = 0 to cityCount
Dim city as string = cbCity.SelectedValue.ToString()
worker.RunWorkerAsync
worker.RunWorkerCompleted
cbCity.SelectedIndex += 1
Next
Here's the thing. Wouldn't the above PseudoCode run the worker.RunWorkerCompleted while worker.RunWorkerAsync is still running? Will it wait for worker.RunWorkerAsync to be completed and finished and then execute worker.RunWorkerCompleted? I am using BackgroundWorker to fill the UI without freezing it and the city variable is being updated in every iteration and used inside RunWorkerAsync. So, essentially, I am trying to execute worker.RunWorkerAsync completely and then move onto the next line and continue the loop.
I am sorry if my language doesn't make sense. I have researched about this and tried several methods, and I am here because none of them worked. I can't share the complete code due to some copyrights issues, but I will be happy to provide more information.
RunWorkerCompleted is called automatically when RunWorkerAsync has finished (please see the BackgroundWorker Class documentation).
The loop should be in the BGW, along with the code you want to run at the end of each iteration.
(Note that the BackgroundWorker.ReportProgress Method can take an Object as its second parameter, so if you make a suitable Class to pass, you can send anything you want to the ProgressChanged handler.)