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