在C#中制作一个简单的计时器

时间:2014-08-08 20:49:38

标签: c# android xamarin

我还是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

1 个答案:

答案 0 :(得分:6)

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

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


2 - 另一种更清晰的方法是使用C#的Language-level support for asynchrony,这样就无需手动封送到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#编译器会自动计算出来。