[英]Timer doesn't contain in System.Threading at Xamarin.Forms
我在Xamarin.Android
使用了System.Threading.Timer
。
我如何在Xamarin.Forms
使用相同的類? (我想從Xamarin.Fornd中的Xamarin.Android轉移我的項目)
public static System.Threading.Timer timer;
if (timer == null)
{
System.Threading.TimerCallback tcb = MyMethod;
timer = new System.Threading.Timer(tcb, null, 700, System.Threading.Timeout.Infinite);
}
else
{
timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
timer.Change(700, System.Threading.Timeout.Infinite);
}
System.Threading.Timer
在PCL代碼中不可用。 您可以使用Xamarin.Forms.Device.StartTimer
方法,如下所述: http : //developer.xamarin.com/api/member/Xamarin.Forms.Device.StartTimer/
對於PCL,您可以使用async / await功能創建自己的功能。 這種方法的另一個優點 - 您的計時器方法實現可以等待計時器處理程序內的異步方法
public sealed class AsyncTimer : CancellationTokenSource
{
public AsyncTimer (Func<Task> callback, int millisecondsDueTime, int millisecondsPeriod)
{
Task.Run(async () =>
{
await Task.Delay(millisecondsDueTime, Token);
while (!IsCancellationRequested)
{
await callback();
if (!IsCancellationRequested)
await Task.Delay(millisecondsPeriod, Token).ConfigureAwait(false);
}
});
}
protected override void Dispose(bool disposing)
{
if (disposing)
Cancel();
base.Dispose(disposing);
}
}
用法:
{
...
var timer = new AsyncTimer(OnTimer, 0, 1000);
}
private async Task OnTimer()
{
// Do something
await MyMethodAsync();
}
嗨,我在Xamarin.forms中找到了計時器的解決方案
Device.StartTimer(TimeSpan.FromMilliseconds(1000), OnTimerTick);
// TimeSpan.FromMilliseconds(1000)以毫秒為單位指定時間// OnTimerTick它將執行的函數返回布爾值
private bool OnTimerTick(){//要執行的代碼lblTime.Text = newHighScore .ToString(); newHighScore ++; 返回true; }
我希望你能輕易理解我的觀點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.