c# - 为什么定时器不启动?
问题描述
这是增加一个数字并在 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());
};
推荐阅读
- for-loop - 进度条 Dos
- machine-learning - 提取过程后的特征选择
- c# - 如何在任务完成之前返回但保持运行?
- node.js - 如果该函数需要被调用大约 250 次,是否有更聪明的方法来调用返回承诺的函数?
- python - 如何在语音命令识别程序中存储(文件/数据结构)语音命令和响应以提高速度?
- java - 在 Kafka Send() 方法的 Onfailure() 方法调用中获取 Objects 值
- python - 如何逐列屏蔽数组
- c# - 向 ObservableCollection 添加元素会导致异常索引超出范围
- javascript - Eclipse JS 编辑器好慢
- vue.js - Vuetify - 规则应该返回一个字符串或布尔值,而不是收到“未定义”