DharaPPatel
DharaPPatel

Reputation: 12733

wait for a async method to return result in wp7

hello friends i have one code which is as follows :

for (int i = 1; i < 6; i++)
{
    int j = 0;
    Nos[j++] = Config[i];

    var xmladd = "uri to download data";
    WebClient _proxy2 = new WebClient();
    _proxy2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted);
    _proxy2.DownloadStringAsync(new Uri(xmladd));

    string msg = Config[11] + ":" + Config[12] + " .My Current Location is " + Properties.address + " , Latitude : " + clslatlong.ReturnLat() + " , Longitude : " + clslatlong.ReturnLongi(); 
}

here problem is that completed event is not fired immedietely and keep on executing the further code but my next code is based on the result returned by the completed event what should be done in this kinda situation ? my code should wait to get the response from completed event and then proceed further please help.

Upvotes: 0

Views: 902

Answers (3)

Stephen Cleary
Stephen Cleary

Reputation: 456322

Asynchronous programming can get messy; the correct way to do it is via Johan Paul's answer: split up your function and put part of it in the event handler. Your code will end up quite messy because you're performing an asynchronous operation in a loop.

Your question has both WP7 and WP7.1 tags; if you can get away with just supporting WP7.1, then you have the option of the Microsoft.Bcl.Async library (currently in Beta). This enables async/await on WP7.1, which is much easier:

for (int i = 1; i < 6; i++)
{
  int j = 0;
  Nos[j++] = Config[i];

  var xmladd = "uri to download data";
  WebClient _proxy2 = new WebClient();
  var result = await _proxy2.DownloadStringTaskAsync(xmladd);

  ...
}

Upvotes: 1

Johan Paul
Johan Paul

Reputation: 2456

You should continue your code execution in the request complete handler, if it's depending on the result. This is how event driven or async coding works.

Upvotes: 2

Related Questions