用c#制作一个简单的计时器

本文关键字:一个 简单 计时器 | 更新日期: 2023-09-27 18:17:16

我还是c#新手,我不知道如何每隔十秒调用updateTime()方法

public class MainActivity : Activity
{
    TextView timerViewer;
    private CountDownTimer countDownTimer;
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.Main);
        timerViewer = FindViewById<TextView> (Resource.Id.textView1);
        // i need to invoke this every ten seconds
        updateTimeinViewer();
    }
    protected void updateTimeinViewer(){
        // changes the textViewer
    }
}

如果有办法创建一个新的线程或类似的东西,我将请得到一些帮助。

我使用Xamarin Studio

用c#制作一个简单的计时器

1 -在c#中通常的方法是使用System.Threading.Timer,如:

int count = 1;
TextView timerViewer;
private System.Threading.Timer timer;
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);
    timerViewer = FindViewById<TextView>(Resource.Id.textView1);
    timer = new Timer(x => UpdateView(), null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
}
private void UpdateView()
{
    this.RunOnUiThread(() => timerViewer.Text = string.Format("{0} ticks!", count++));
}

注意,在访问UI元素时,需要使用Activity.RunOnUiThread()来避免跨线程冲突。


2—另一种更简洁的方法是利用c#语言级别对异步的支持,这样就不需要手动来回封送UI线程了:

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
        timerViewer = FindViewById<TextView>(Resource.Id.textView1);
        RunUpdateLoop();
    }
    private async void RunUpdateLoop()
    {
        int count = 1;
        while (true)
        {
            await Task.Delay(1000);
            timerViewer .Text = string.Format("{0} ticks!", count++);
        }
    }

注意这里不需要Activity.RunOnUiThread()。c#编译器会自动计算出