public decimal CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
{
string url = string.Format(urlPattern, fromCurrency, toCurrency);
using (var wc = new WebClient())
{
var json = wc.DownloadString(url);
Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.Parse(json);
decimal exchangeRate = (decimal)token.SelectToken("rate");
var result = (amount * exchangeRate);
return result;
}
}
大家好,每当我尝试在输入字段中插入新数字时,这就是我正在使用的代码,在显示下一个数字之前,会有1秒的延迟。知道我该如何解决吗? :o
答案 0 :(得分:0)
延迟必须仅是由于下载字符串和处理它所花费的时间。您在这里唯一能做的就是异步下载字符串,这将减少主线程的负载,从而稍微减少延迟。
public async decimal CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
{
string url = string.Format(urlPattern, fromCurrency, toCurrency);
var wc = new WebClient();
var json = await wc.DownloadStringAsync(url);
Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.Parse(json);
decimal exchangeRate = (decimal)token.SelectToken("rate");
var result = (amount * exchangeRate);
return result;
}
答案 1 :(得分:0)
那是对我有用的代码,直到将值存储在ConcurrentDictionary中之后,一切都变得很顺利为止,您会滞后。
static ConcurrentDictionary<string, decimal> cachedDownloads =
new ConcurrentDictionary<string, decimal>();
public async Task<decimal> CurrencyConversionAsync(decimal amount, string fromCurrency, string toCurrency)
{
string content = "";
string url = string.Format(urlPattern, fromCurrency, toCurrency);
Decimal result = 0;
decimal exchangeRate = 0;
if (CheckForInternetConnection() == false)
{
result = amount * decimal.Parse("1.11");
return result;
}
if (cachedDownloads.TryGetValue(content, out exchangeRate))
{
result = (amount * exchangeRate);
return result;
}