This is likely to be a(nother) noob question, but I’m not sure how to do this.
I have piece of code within a private method which refers to a static method.
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(requestUri));
}
The static method it refers to:
static void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var xmlElm = XElement.Parse(e.Result);
var status = (from elm in xmlElm.Descendants()
where elm.Name == "status"
select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants()
where elm.Name == "formatted_address"
select elm).FirstOrDefault();
formatted = res.Value;
}
}
Now I need the content of the static method to replace the content of the WebClient.
Like:
using (WebClient wc = new WebClient())
{
var xmlElm = XElement.Parse(e.Result);
var status = (from elm in xmlElm.Descendants()
where elm.Name == "status"
select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants()
where elm.Name == "formatted_address"
select elm).FirstOrDefault();
formatted = res.Value;
}
}
Since I’m not sure where “e” originates from, I do not know how to get it working.
You seem to be missing the point of asynchronous call. The whole point in this is to start the execution of the asynchronous method then keep going with your code forgetting all about the method, leaving only a callback method to handle its response.
To make things short and simple, there is no way you can use the variable
formattedthe way you want, as you can use the result of the asynchronous call only in the callback method.You can however have the whole code inside the same block (no need for separate method) using such lambda syntax for anonymous method:
This for example will populate a label in the page with the results, once they are ready.
If you want to wait until the load is finished, simply use the ordinary
DownloadStringmethod: