单体定时器 [英] monodroid Timer

查看:28
本文介绍了单体定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use a timer in my C# monodroid program for android 2.2, but it doesnt work. here is my code:

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).

System.Timers.Timer will be running on a separate (non-UI) thread. Consequently, your OnTimeEvent() method is incorrect, as it will be updating a UI instance (txv1) from a non-UI thread.

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

You need to use Activity.RunOnUiThread() to update the UI from a background thread:

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

这篇关于单体定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆