将计时器添加到Xamarin应用程序(c#)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将计时器添加到Xamarin应用程序(c#)相关的知识,希望对你有一定的参考价值。
答案
您可以使用System.Threading.Timer类,该类在Xamarin文档中有记录:https://developer.xamarin.com/api/type/System.Threading.Timer/
或者,对于Xamarin.Forms,您可以通过Device类访问跨平台的Timer:
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
// called every 1 second
// do stuff here
return true; // return true to repeat counting, false to stop timer
});
另一答案
如果你只需要Android就可以使用
System.Threading.Timer
在使用Xamarin Forms的共享代码中,您可以使用
Device.StartTimer(...)
或者您可以使用以下高级功能实现一个yourselfe:
public sealed class Timer : CancellationTokenSource {
private readonly Action _callback;
private int _millisecondsDueTime;
private readonly int _millisecondsPeriod;
public Timer(Action callback, int millisecondsDueTime) {
_callback = callback;
_millisecondsDueTime = millisecondsDueTime;
_millisecondsPeriod = -1;
Start();
}
public Timer(Action callback, int millisecondsDueTime, int millisecondsPeriod) {
_callback = callback;
_millisecondsDueTime = millisecondsDueTime;
_millisecondsPeriod = millisecondsPeriod;
Start();
}
private void Start() {
Task.Run(() => {
if (_millisecondsDueTime <= 0) {
_millisecondsDueTime = 1;
}
Task.Delay(_millisecondsDueTime, Token).Wait();
while (!IsCancellationRequested) {
//TODO handle Errors - Actually the Callback should handle the Error but if not we could do it for the callback here
_callback();
if(_millisecondsPeriod <= 0) break;
if (_millisecondsPeriod > 0 && !IsCancellationRequested) {
Task.Delay(_millisecondsPeriod, Token).Wait();
}
}
});
}
public void Stop() {
Cancel();
}
protected override void Dispose(bool disposing) {
if (disposing) {
Cancel();
}
base.Dispose(disposing);
}
}
另一答案
你可以随时使用
Task.Factory.StartNewTaskContinuously(YourMethod, new CancellationToken(), TimeSpan.FromMinutes(10));
请务必将以下类添加到项目中
static class Extensions
{
/// <summary>
/// Start a new task that will run continuously for a given amount of time.
/// </summary>
/// <param name="taskFactory">Provides access to factory methods for creating System.Threading.Tasks.Task and System.Threading.Tasks.Task`1 instances.</param>
/// <param name="action">The action delegate to execute asynchronously.</param>
/// <param name="cancellationToken">The System.Threading.Tasks.TaskFactory.CancellationToken that will be assigned to the new task.</param>
/// <param name="timeSpan">The interval between invocations of the callback.</param>
/// <returns>The started System.Threading.Tasks.Task.</returns>
public static Task StartNewTaskContinuously(this TaskFactory taskFactory, Action action, CancellationToken cancellationToken, TimeSpan timeSpan
, string taskName = "")
{
return taskFactory.StartNew(async () =>
{
if (!string.IsNullOrEmpty(taskName))
{
Debug.WriteLine("Started task " + taskName);
}
while (!cancellationToken.IsCancellationRequested)
{
action();
try
{
await Task.Delay(timeSpan, cancellationToken);
}
catch (Exception e)
{
break;
}
}
if (!string.IsNullOrEmpty(taskName))
{
Debug.WriteLine("Finished task " + taskName);
}
});
}
}
另一答案
是的,你可以使用System.Timers.Timer
。
在Android中,我们可以像这样使用java.util.Timer:
private int i;
final Timer timer=new Timer();
TimerTask task=new TimerTask() {
@Override
public void run() {
if (i < 60) {
i++;
} else {
timer.cancel();
}
Log.e("time=",i+"");
}
};
timer.schedule(task, 0,1000);
在Xamarin.Android中我们也可以像这样使用java.util.Timer:
[Activity(Label = "Tim", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
Timer timer = new Timer();
timer.Schedule(new MyTask(timer),0,1000);
}
}
class MyTask : TimerTask
{
Timer mTimer;
public MyTask(Timer timer) {
this.mTimer = timer;
}
int i;
public override void Run()
{
if (i < 60)
{
i++;
}
else {
mTimer.Cancel();
}
Android.Util.Log.Error("time",i+"");
}
}
以上是关于将计时器添加到Xamarin应用程序(c#)的主要内容,如果未能解决你的问题,请参考以下文章
Xamarin.Android RunOnUIThread 和 onTimedEvent 延迟/滞后(我正在尝试显示倒数计时器)