i having some hard time on this, i’m trying to get my first WP7 app out.
I have an method that download the html from a website and regex it, but the problem is, when i click the button for the first time, nothing happens, on the second try, it fills the grid perfectly, when i was debugging i saw the string with the HTML is already assigned correctly before the method even starts. So, the question is, what is the simplest way to wait for async method to finish?
I’ve searched about CTP async and some other ways, but i can’t manage to make it work.
Here’s is the code
public static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
doc = e.Result;
}
public static List<Row> Search(string number)
{
WebClient wClient = new WebClient();
sNumber = number;
int i = 0;
DateTime datetime;
wClient.DownloadStringAsync(new Uri(sURL + sNumber));
wClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
/*More code*/
}
The button calls the method Search() and uses the list returned to fill the grid.
The
wClient.DownloadStringAsync(new Uri(sURL + sNumber));method executes after all the code in that method is executed.1) At first
docis null2) Then you call
wClient.DownloadStringAsync(new Uri(sURL + sNumber));but doesn’t execute!!3) Then you return doc (which is still null)
4) After all this,
wClient.DownloadStringAsync(new Uri(sURL + sNumber));is executed anddocis filled.That is why when you press the Search button for the 2nd time, the grid is filled perfectly
N.B. You must register the
DownloadStringCompletedEventHandlerbefore calling the async method. And you only have to register this event handler once, i.e. in the constructor, because you are adding an event handler everytime this method is executed. So if you press the Search button for 5 times, the grid is filled for 5 times although you don’t noticeOne solution would be:
Here’s is the code