取消了,当机器人的AsyncTask不会停止,为什么? [英] Android AsyncTask won't stop when cancelled, why?

查看:135
本文介绍了取消了,当机器人的AsyncTask不会停止,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我在活动的的onPause生命周期事件关闭的AsyncTask的,所以当有人离开应用程序不运行,但它一直尽管这样下去。我加了一些跟踪和这个片段显示了这个问题。

I've an AsyncTask that I shut down in the Activity's onPause lifecycle event, so it doesn't run when someone leaves the app, but it keeps going despite this. I added some tracing and this snippet shows the problem.

    Trace.d(TAG,"Task state: " + myTask.getStatus() );
    myTask.cancel(true);
    Trace.d(TAG,"Task state: " + myTask.getStatus() );

输出:

Task state: RUNNING
Task state: RUNNING

为什么cancel()方法没有对任务的状态有什么影响?我注意到文档说取消等方法将尝试停止任务,但在什么情况下会失败?任务肯定是运行,因为它是输出日志输出每10秒钟,你可以在上面看到其状态返回运行。

Why is the cancel() method not having any effect on the state of the task? I notice the docs say the cancel method will "attempt" to stop the task, but under what circumstances will it fail? The task is definitely running as it is outputting log output every ten seconds, and as you can see above its status is returned as running.

更新:我添加了跟踪,​​以显示我的isCancelled()状态很好,确实发生了改变。因此,呼吁取消(真)从假更改取消状态为真,但显然有对现状没有影响,或停止线程。

Update: I added tracing to show me the isCancelled() state as well and that DOES change. So the call to cancel(true) is changing the cancelled state from false to true, but apparently having no effect on the Status, or stopping the thread.

推荐答案

我挖更深,记得我的线程调用包含此相当写的不好的方法,产生另一个线程内部的一个我需要取消:

I dug deeper and remembered that my thread was calling a rather badly written method containing this, producing another thread inside the one I need to cancel:

public static void haveASleep(int milliseconds)
{
    try
    {
        Thread.sleep(milliseconds);
    }
    catch (InterruptedException ie)
    {
        Trace.w(TAG,"Sleep interrupted");
    }
}

所以,发生了什么事是,AsyncTask的线程调用这个方法来等待一段时间,而睡眠中的cancel()方法调用发生在AsyncTask的,这将导致在线程睡眠异常。我的code无助地抓住了,而不是用它来关闭AsyncTask的吸收这个异常。

So what was happening was that the AsyncTask thread calls this method to wait a while, and during the sleep the cancel() method call occurs on the AsyncTask, which causes an exception in the thread sleep. My code unhelpfully caught and absorbed that exception, instead of using it to shut down the AsyncTask.

解决的办法是找对睡眠异常,如果它被抛出,悄悄地退出线程。该应用程序现在将按预期,但...

The solution was to look for an exception on the sleep, and if it is thrown, to quietly exit the thread. The app now works as expected, BUT...

取消()方法调用之后的状态保持运行,但我怀疑这是因为在那一刻,它仍在运行,而操作系统还没有关闭它。我不知道如果这是真的,但是这是我最好的估计。

The status immediately after the cancel() method call remains RUNNING, but I suspect this is because at that moment it is still running, and the OS has not yet shut it down. I have no idea if that's true, but that's my best estimate.

这篇关于取消了,当机器人的AsyncTask不会停止,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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