简体   繁体   English

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

[英]Making API call every 5 seconds in C#

I'm trying to develop a mobile app on Xamarin Forms platform.I'm getting data from API.API call only happened once only when the application is opened. 我正在尝试在Xamarin Forms平台上开发移动应用程序。我正在从API获取数据.API调用仅在打开应用程序时发生一次。 I'm Listing livescores between teams in a ListView . 我在ListView中列出团队之间的比分。 For example the minutes of the match 25 for now.I'm waiting 2 minutes and nothing changed. 例如现在比赛的分钟数是25。我正在等待2分钟,什么都没有改变。 The minute is the same on my ListView.When I close and open the app again minute is changing.I just want to make call every 5 second to refresh the data without close the application. 我的ListView上的分钟是相同的。当我关闭并再次打开应用程序时,分钟改变了,我只想每5秒打电话一次以刷新数据而不关闭应用程序。 Here is my code. 这是我的代码。

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;

    }

What you can do is implement my special PollingTimer.cs class: 您可以做的是实现我的特殊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();
        }
    }
}

Then what you can do following that is in your page that you want to make a call every 5 seconds from, in the constructor at the end of it you can write this line of code: 然后,您要执行的操作是在您要每5秒调用一次的页面中,在其末尾的构造函数中,您可以编写以下代码行:

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

This will run your method every 5 seconds. 这将每5秒运行一次您的方法。 To make your method work with the pollingtimer you must edit your method to a void and return the value to a global variable like so: 要使您的方法与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;



        }

Then from there you can check your live score data in other methods. 然后,您可以从那里以其他方法查看实时比分数据。 Then in your OnAppearing method you can run 然后,在您的OnAppearing方法中,您可以运行

timer.Start();

and in your OnDisappearing method you can run 并在您的OnDisappearing方法中可以运行

timer.Stop();

have a play with it and see if you can put it in better places for optimal performance etc. 试一下,看看是否可以将其放在更好的位置以获得最佳性能等。

You could use the System.Threading.Timer object 您可以使用System.Threading.Timer对象

and simply initialize it like this 然后像这样初始化它

`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`

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

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