c# - 如何在 Xamarin Forms 中每 x 秒调用一次方法 x 时间?
问题描述
我正在 Xamarin Forms 中制作一个应用程序,在该应用程序中,我需要每 x 次调用一个方法,持续 x 时间(例如,每 5 秒持续 2 分钟)。怎么做到呢?
我只找到了有关如何每 x 次调用一个方法的信息,但这对于我正在寻找的内容来说还不够。
这是我尝试过的。MyMethod
15 秒后调用:
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 时间。
解决方案
你可以这样做:
您可能需要一个在后台运行的线程:
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);
}
});
}
推荐阅读
- javascript - html中的随机javascript图像
- windows - 为什么characteristic.ReadValueAsync() 有时会抛出ObjectDisposedException?
- c# - 什么是匹配逗号-引号-逗号的正则表达式?
- android - 中心裁剪比例类型在 android 图像视图中不起作用
- java - 如果文件行以 001 开头,则将最后一行转换为字符串 JAVA
- java - 如何递归删除非搜索二叉树的节点?
- sql - SQL 对不同日期范围的行求和
- matlab - 根据日期和时间MATLAB从datetime中选择数据
- yammer - 数据导出 Yammer API
- sql - 是否可以在给定触发器的情况下在不同时间两次更新一行?