首页 > 解决方案 > 如何在 Xamarin Forms 中每 x 秒调用一次方法 x 时间?

问题描述

我正在 Xamarin Forms 中制作一个应用程序,在该应用程序中,我需要每 x 次调用一个方法,持续 x 时间(例如,每 5 秒持续 2 分钟)。怎么做到呢?

我只找到了有关如何每 x 次调用一个方法的信息,但这对于我正在寻找的内容来说还不够。

这是我尝试过的。MyMethod15 秒后调用:

await Task.Delay(new TimeSpan(0, 0, 15)).ContinueWith(async o =>
{
    MyMethod();
});

MyMethod每 5 秒调用一次:

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(5);

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();
}, null, startTimeSpan, periodTimeSpan);

我需要的是MyMethod每 x 秒调用 x 时间。

标签: c#xamarin.forms

解决方案


你可以这样做:

您可能需要一个在后台运行的线程:

private async void CallMethodEveryXSecondsYTimes(int waitSeconds, int durationSeconds) 
{
    await Task.Run(() => {
        var end = DateTime.Now.AddSeconds(durationSeconds);
        while (end > DateTime.Now)
        {
                Dispatcher.BeginInvokeOnMainThread(() =>
                {
                    YourMethod();
                });
                Thread.Sleep(waitSeconds*1000);
        }
    });
}

推荐阅读