xamarin C#中每5秒调用一次API

ztyzrc3y  于 5个月前  发布在  C#
关注(0)|答案(2)|浏览(73)

我试图在Xamarin Forms平台上开发一个移动的应用程序。我从API获取数据。API调用只发生一次,只有当应用程序打开时。我在ListView中列出球队之间的livescores。例如,比赛的分钟25现在。我等待2分钟,没有任何变化。分钟在我的ListView上是相同的。当我关闭并再次打开应用程序时,分钟正在变化。我只是想每5秒调用一次刷新数据而不关闭应用程序。下面是我的代码。

public List<liveScoreData>liveScore() 
    {
        var result = new List<liveScoreData>();
        try
        {

            Guid guidSifre = Guid.NewGuid();
            string guid = guidSifre.ToString();
            string result = CreateMD5forChecksum(guid);

            using (var client = new WebClient())
            {
                var values = new NameValueCollection();
                values["result"] = result;
                values["guid"] = guid;

                var response = client.UploadValues("http://abcd.com/admin/LiveScore", values);

                var responseString = Encoding.Default.GetString(response);

                var responseResult = JsonConvert.DeserializeObject(responseString);
                result = JsonConvert.DeserializeObject<List<liveScoreData>>(responseResult.ToString());

                Mehmet.liveScoreDataList = result;

            }
        }
        catch (Exception ex)
        {
            var exc = ex;
        }

        return result;

    }

字符串

41zrol4v

41zrol4v1#

你可以做的是实现我的特殊PollingTimer.cs类:

using System;
using System.Threading;
using Xamarin.Forms;

namespace AppNamespace.Helpers
{
    /// <summary>
    /// This timer is used to poll the middleware for new information.
    /// </summary>
    public class PollingTimer
    {
        private readonly TimeSpan timespan;
        private readonly Action callback;

        private CancellationTokenSource cancellation;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:CryptoTracker.Helpers.PollingTimer"/> class.
        /// </summary>
        /// <param name="timespan">The amount of time between each call</param>
        /// <param name="callback">The callback procedure.</param>
        public PollingTimer(TimeSpan timespan, Action callback)
        {
            this.timespan = timespan;
            this.callback = callback;
            this.cancellation = new CancellationTokenSource();
        }

        /// <summary>
        /// Starts the timer.
        /// </summary>
        public void Start()
        {
            CancellationTokenSource cts = this.cancellation; // safe copy
            Device.StartTimer(this.timespan,
                () => {
                    if (cts.IsCancellationRequested) return false;
                    this.callback.Invoke();
                    return true; // or true for periodic behavior
            });
        }

        /// <summary>
        /// Stops the timer.
        /// </summary>
        public void Stop()
        {
            Interlocked.Exchange(ref this.cancellation, new CancellationTokenSource()).Cancel();
        }
    }
}

字符串
然后你可以做的是在你的页面中,你想每5秒调用一次,在它末尾的构造函数中,你可以写这行代码:

timer = new PollingTimer(TimeSpan.FromSeconds(5), liveScore);


这将每5秒运行一次你的方法。为了让你的方法与pollingtimer一起工作,你必须将你的方法编辑为void,并将值返回给一个全局变量,如下所示:

//Make a global variable for your method to access
  List<liveScoreData> globalLiveScore = new List<liveScoreData>();

      public void liveScore() 
        {
            var result = new List<liveScoreData>();
            try
            {

                Guid guidSifre = Guid.NewGuid();
                string guid = guidSifre.ToString();
                string result = CreateMD5forChecksum(guid);


                using (var client = new WebClient())
                {
                    var values = new NameValueCollection();
                    values["result"] = result;
                    values["guid"] = guid;


                    var response = client.UploadValues("http://abcd.com/admin/LiveScore", values);

                    var responseString = Encoding.Default.GetString(response);


                    var responseResult = JsonConvert.DeserializeObject(responseString);
                    result = JsonConvert.DeserializeObject<List<liveScoreData>>(responseResult.ToString());


                    Mehmet.liveScoreDataList = result;

                }
            }
            catch (Exception ex)
            {
                var exc = ex;
            }

            globalLiveScore = result;


        }


然后从那里你可以用其他方法检查你的实时分数数据。

timer.Start();


在OnDisappearing方法中,

timer.Stop();


尝试一下,看看你是否可以把它放在更好的地方,以获得最佳性能等。

k2fxgqgv

k2fxgqgv2#

可以使用System.Threading.Timer对象
然后简单地初始化它

`System.Threading.Timer myTimer = new System.Threading.Timer((e) =>
{
    liveScore(); //your function call
}, null, 
TimeSpan.FromSeconds(0), //start immediately
TimeSpan.FromSeconds(5)); //execute every 5 secs`

字符串

相关问题