我正在使用 Xamarin 和 MvvmCross 构建跨平台应用程序。我需要每分钟调用服务器进行更新(稍后我将移动到推送通知)但我无法在我的核心项目中设置计时器。我看过 MvvmCross N+42,但我相信目标项目较旧,允许计时器。下面是我的目标框架。
有没有更好的方法让我不断调用调用服务的方法?
- .NET Framework 4.5 及更高版本
- Windows 应用商店应用 (Windows 8) 及更高版本
- Windows 手机 8
- Xamarin.Android
- Xamarin.iOS
最佳答案
@stevemorgan 的回答非常有效。 我基于该代码创建了一个 Timer 实用程序,以使其更易于重用。 我还添加了一个“runOnce”参数,它将在第一次滴答后停止计时器
public class PclTimer
{
public bool IsRunning { get; private set; }
public TimeSpan Interval { get; set; }
public Action Tick { get; set; }
public bool RunOnce { get; set; }
public Action Stopped { get; set; }
public Action Started { get; set; }
public PclTimer(TimeSpan interval, Action tick = null, bool runOnce = false)
{
Interval = interval;
Tick = tick;
RunOnce = runOnce;
}
public PclTimer Start()
{
if (!IsRunning)
{
IsRunning = true;
Started?.Invoke();
var t = RunTimer();
}
return this;
}
public void Stop()
{
IsRunning = false;
Stopped?.Invoke();
}
private async Task RunTimer()
{
while (IsRunning)
{
await Task.Delay(Interval);
if (IsRunning)
{
Tick?.Invoke();
if (RunOnce)
{
Stop();
}
}
}
}
}
我在 MvvmCross 中使用它没有任何问题:
timer = new Timer(TimeSpan.FromSeconds(4),
() => ShowViewModel<UserMatchViewModel>(), true)
.Start();
关于c# - PCL .NET 4.5 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151143/