如何在Xamarin中添加定时器?

6

我需要一个计时器,倒数60秒。我对Xamarin很陌生,不知道它接受什么。这将用于Android。

有任何建议如何开始吗?

你能使用System.Timers.Timer吗?


System.Threading.Timer - Jason
可能是如何在C#控制台应用程序中添加计时器的重复问题。 - Brandon Minnick
3
你可以使用System.Timers.Timer在Xamarin中,这是最好的选择,并且我经常大量使用它。 - rubo
4个回答

11

您可以使用 System.Threading.Timer 类,该类在 Xamarin 文档中有记录:https://developer.xamarin.com/api/type/System.Threading.Timer/

另外,在 Xamarin.Forms 中,您可以通过 Device 类访问跨平台计时器:

Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
    // called every 1 second
    // do stuff here

    return true; // return true to repeat counting, false to stop timer
});

3
当应用程序进入后台时,Device.Timer停止计时。这仅适用于iOS设备。 - Poornesh V

3
如果您只需要Android,您可以使用。
System.Threading.Timer

在使用Xamarin Forms的共享代码中,您可以使用

Device.StartTimer(...)

或者您可以自己实现一个具有高级功能的解决方案,例如:

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);
    }

}

2

是的,你可以使用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: 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+"");
    }
}

0

你总是可以使用

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);
            }
        });
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接