繁体   English   中英

Xamarin 表单中的输入延迟?

[英]Entry input lag in Xamarin forms?

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

延迟只能是由于下载字符串和处理它所花费的时间。 您在这里唯一可以做的就是异步下载字符串,这将减少主线程中的负载以稍微减少延迟。

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;
}

那是对我有用的代码,只有在值存储在 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;

            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM