我有一个方法如下:
public decimal GetExchangeRate(string fromCurrency, string toCurrency)
{
GoogleCurrencyService googleCurrencyService = new GoogleCurrencyService();
return googleCurrencyService.GetRateForCurrency(fromCurrency, toCurrency);
}
和另一个类如下
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
变量 ExchangeRate 总是为零,所以我相信函数调用“GetRateForCurrency”在异步回调被调用之前返回。我如何确保不会发生这种情况,因为我需要在返回之前设置变量 ExchangeRate。谢谢。另外,我注意到回调永远不会被调用,因为我在其中有一个断点,并且异常也没有被调用。所以我不知道问题出在哪里。感谢任何帮助。