c# - 机器人计时器

标签 c# timer xamarin.android

我想在 android 2.2 的 C# monodroid 程序中使用计时器,但它不起作用。 这是我的代码:

using System;
using System.Timers;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Util;

namespace MonoAndroidApplication1
{
[Activity(Label = "MonoAndroidApplication1", MainLauncher = true, Icon=drawable/icon")]
public class Activity1 : Activity
{
    int count = 1;
    TextView txv1;
    System.Timers.Timer t1;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        txv1 = FindViewById<TextView>(Resource.Id.txv1);
        DateTime dt = DateTime.Now;
        txv1.Text = dt.ToShortTimeString();
        t1 = new System.Timers.Timer(200);
        t1.Elapsed += new ElapsedEventHandler(OnTimeEvent);
        t1.Interval = 200;
        t1.Enabled = true;
        t1.Start();


    }
    private void OnTimeEvent(object source, ElapsedEventArgs e)
    {
        txv1.Text = count.ToString();
        count++;
    }
}
}

请帮助我。

最佳答案

System.Timers.Timer 将在单独的(非 UI)线程上运行。因此,您的 OnTimeEvent() 方法不正确,因为它将从非 UI 线程更新 UI 实例 (txv1)。

您需要使用 Activity.RunOnUiThread()从后台线程更新 UI:

private void OnTimeEvent(object source, ElapsedEventArgs e)
{
    RunOnUiThread(delegate {
        txv1.Text = count.ToString ();
        count++;
    });
}

关于c# - 机器人计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7097729/

相关文章:

c# - 方法已执行但未生效

cocoa - 从计时器停止 NSRunLoop

javascript - 如何在for循环中设置延迟

android - SQLite 与 Realm 在黑客数据安全方面的比较

c# - 如果以 xamarin 形式选择它,如何清除选择器?

c# - 在 asp.net 中的同一服务器上下载应用程序根文件夹之外的文件

c# - 如何使用代码优先 Entity Framework 设置默认日期

android - Xamarin,覆盖自定义渲染器中的焦点更改会阻止发生焦点事件

c# - 在 c# 中将 int 添加到 char 以将其 ascii 值向上移动(就像在 c++ 中一样)

Java 定时器类 : timer tasks stop to execute if in one of the tasks exception is thrown