繁体   English   中英

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

[英]making a simple timer in C#

我还是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-在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# 对异步语言级别支持 ,从而消除了手动往返于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#编译器会自动发现这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM