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

时间:2018-11-19 11:54:25

标签: c# api xamarin call

我正在尝试在Xamarin Forms平台上开发移动应用程序。我从API获取数据。API调用仅在打开应用程序时发生一次。我在ListView中列出团队之间的比分。例如现在比赛的分钟数是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;

    }

2 个答案:

答案 0 :(得分:0)

您可以做的是实现我的特殊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;



        }

然后从那里可以用其他方法检查实时比分数据。然后,您可以在OnAppearing方法中运行

timer.Start();

,然后在您的OnDisappearing方法中运行

timer.Stop();

试一下,看看是否可以将其放在更好的位置以获得最佳性能等。

答案 1 :(得分:0)

您可以使用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`