简体   繁体   English

Android:清理AsyncTask

[英]Android: Clean up AsyncTask

Over time my app using a lot of AsyncTasks, and I noticed in the debugger that they don't go away and even when they are done they still show up as an active thread. 随着时间的流逝,我的应用程序使用了大量的AsyncTasks,我在调试器中注意到它们并不会消失,即使完成后,它们仍会显示为活动线程。 Is there any way after the task is done to tell the garbage collector to kill it? 任务完成后有什么办法告诉垃圾收集器杀死它?

EDIT: Lenik pointed out below that my original answer was not the proper android way to cancel an AsyncTask. 编辑:Lenik在下面指出,我的原始答案不是取消AsyncTask的正确android方法。

AsyncTask has a complete and elegant system for cancelling. AsyncTask具有完整而优雅的取消系统。 Call the cancel(true) method on your task when you're ready to cancel. 准备取消时,在您的任务上调用cancel(true)方法。 If you're running an internal loop, use isCancelled() to check the status, and exit the loop appropriately if it returns true . 如果您正在运行内部循环,请使用isCancelled()检查状态,如果返回true适当退出循环。 This has the added benefit of calling your onCancelled(Object) method on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished. 这具有在调用cancel(boolean)doInBackground(Object[])完成之后在UI线程上调用doInBackground(Object[]) onCancelled(Object)方法的额外好处。 Then set the reference to your task to null. 然后将对您的任务的引用设置为null。

Thanks Lenik! 谢谢勒尼克! If you post an answer, I'll delete this one so you receive credit. 如果您发布答案,我将删除该答案,以便您获得积分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM