I have a method as follows:
public decimal GetExchangeRate(string fromCurrency, string toCurrency)
{
GoogleCurrencyService googleCurrencyService = new GoogleCurrencyService();
return googleCurrencyService.GetRateForCurrency(fromCurrency, toCurrency);
}
and another class as follows
public class GoogleCurrencyService
{
public decimal GetRateForCurrency(string fromCurrency, string toCurrency)
{
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(StringDownloadCompleted);
client.DownloadStringAsync(new Uri(_requestUri + fromCurrency + "=?" + toCurrency));
}
catch (Exception)
{
ExchangeRate = 0;
}
return ExchangeRate;
}
private void StringDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
_response = e.Result;
ExchangeRate = ParseResponseAndGetExchangeRate();
}
}//class GoogleCurrencyService
the variable ExchangeRate always come out as zero, so I believe the function call “GetRateForCurrency” returns before the async callback gets called. How do I make sure that does not happen as I need the variable ExchangeRate to be set before being returned. Thanks. Also, I have noticed that the callback never gets called as I have a breakpoint in it and the exception as well which does not get called. So I donot know where the problem is.Any help appreciated.
You can use an event wait handle to block the current thread and wait for the async call…
EDIT: The same class using an async pattern
Consuming the async class:
Maybe you’ll have to dispatch the UI changes to ui thread. I not have WP framework here to confirm that this is the case, but I think it is.