making a simple timer in C#

前端 未结 1 1969
-上瘾入骨i
-上瘾入骨i 2021-01-28 09:26

I\'m still new to c# and i dont how to invoke the method updateTime() every ten seconds

public class MainActivity : Activity
{
    TextView timerViewer;
    priv         


        
1条回答
  •  一整个雨季
    2021-01-28 09:49

    1 - One usual way to do that in C# is to use a System.Threading.Timer, like so:

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

    Notice that you need to use Activity.RunOnUiThread() in order to avoid cross-thread violations when accessing UI elements.


    2 - Another, cleaner approach is to make use of C#'s Language-level support for asynchrony, which removes the need to manually marshal back and forth to the UI thread:

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

    Notice there's no need for Activity.RunOnUiThread() here. the C# compiler figures that out automatically.

    0 讨论(0)
提交回复
热议问题