c# - 为什么计时器不启动?

标签 c# android xamarin xamarin.android

这是简单的代码,增加一个数字并将其显示在 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();
         };
    }

最佳答案

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

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

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

关于c# - 为什么计时器不启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54523277/

相关文章:

c# - FluentNhibernate 公式与连接表中的参数进行映射

c# - 使用 asp.net 和 C# 从 javascript 调用外部服务器上的 webservice

c# - 静态构造函数重载?

c# - 使用 NetTopologySuite TransformGeometry 时出错

android - 启动Android模拟器时"There is not enough storage space on the device to store package"

android - 是否需要为所有dpi文件夹提供图像?

android - 通过通知按钮打开蓝牙

android - 如何在按钮单击main.xml后转到下一个布局并在android中再次转到下一个布局

android - 如何从 Xamarin 编写 firebase ServerValue.Timestamp

c# - 恢复数据库时提取 Zip 文件