首页 > 解决方案 > 为什么定时器不启动?

问题描述

这是增加一个数字并在 texView 中显示它的简单代码,但它不起作用,我不知道我的代码有什么问题......

这是我的代码:

protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        TextView textView = FindViewById<TextView>(Resource.Id.textView1);
        Timer timer1 = new Timer();
        timer1.Interval = 1000;
        timer1.Enabled = true;
        timer1.Start();
        timer1.Elapsed += (object sender, ElapsedEventArgs e) =>
         {
             x++;
             textView.Text = x.ToString();
         };
    }

标签: c#androidxamarinxamarin.android

解决方案


由于您没有使用 SynchronizingObject,System.Timers.Timer因此在线程池线程上调用 Elapsed,因此您不在 UI/主线程上(需要执行 UI 更新)。

因此,请使用RunOnUiThread在事件中更新您的 UI:

timer1.Elapsed += (object sender, ElapsedEventArgs e) =>
{
    x++;
    RunOnUiThread(() => button.Text = x.ToString());
};

推荐阅读