【问题标题】:System thread inside a Timer in AndroidAndroid中定时器内的系统线程
【发布时间】:2014-12-14 02:15:48
【问题描述】:

所以我的Activity 中有一个Timer,我想每10 秒运行一次。

我创建了一个System.Threading.Timer

timer = new Timer ((o) => {
    Action syncAct = new Action (async delegate() {
        await FetchData();
    });

    RunOnUiThread (syncAct);
}, null, 0, 10000);

这里的问题是await FetchData() 花费的时间超过 10 秒,这会导致计时器永远持续下去。每次同步完成后,我都需要启动计时器。我该怎么做?

感谢您的宝贵时间。

【问题讨论】:

    标签: c# android multithreading timer xamarin


    【解决方案1】:

    尝试生成一个休眠 10 秒并运行代码的线程。

    大概是这样:

    \\declare doRun as a boolean field
    new Thread()
    {
        public void run()
        {
            yourClass.doRun = true;
            while(yourClass.doRun)
            {
                fetchData();
                try {
                    sleep(10000);
                } catch(InterruptedException e)
                    break; 
                }
            }
        }
    }.start();
    

    doRun 设置为false 以退出线程。 或者您可以将线程分配给变量而不是匿名线程,然后调用yourThread.interrupt();

    【讨论】:

    • 所以我会把它放在我的Timer 中?我需要每 10 秒重复一次。我对此很陌生,所以这是一个快速的问题。 sleep(10000) 是做什么的?我的意思是说,它是否仍然允许用户在睡眠时使用Activity?发生这种情况时,该应用需要可用。
    • @user3866010,不,使用它代替您当前的代码。我写的代码会调用你的fetchData()方法,方法完成后会等待10秒再运行,直到doRun为假。
    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2011-05-21
    相关资源
    最近更新 更多