AsyncTask 超过几秒钟? [英] AsyncTask for longer than a few seconds?

查看:40
本文介绍了AsyncTask 超过几秒钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

API 参考说明,

AsyncTasks 最好用于短期操作(几秒钟最多.)

AsyncTasks should ideally be used for short operations (a few seconds at the most.)

doInBackground 的问题是需要 30 秒,线程池可能会耗尽线程吗?如果这就是原因,如果我确保我的应用程序永远不会有多个这样长时间运行的 doInBackground 同时执行,它会不再是一个问题吗?

Is the problem with a doInBackground that takes, say, 30 seconds that the thread pool might run out of threads? And if that's the reason, would it cease to be a problem if I ensure my app will never have more than one such long running doInBackground executing concurrently?

推荐答案

我相信 AyncTasks 通常仍然与产生它们的前台活动堆栈相关联,因此例如如果一个 Activity 产生一个 AsyncTask,用户离开应用程序,然后操作系统内存不足,它会杀死 Activity 的进程(包括仍在运行的 AsyncTask),并且只希望你恢复状态并重新开始,如果用户恢复/返回到您的应用.

I believe that AyncTasks are in general still tied to the foreground activity stack that spawned them, so that e.g. if an Activity spawns an AsyncTask, the user leaves the app, and then the OS is short of memory, it will kill the Activity's process (including the still-running AsyncTask), and just expect you to restore the state and start over if the user resumes/returns to your app.

对于运行时间较长的任务,尤其是只有一个或几个的任务,您可能需要一个 Service,因为即使您的应用的 UI 为节省内存而关闭,这些任务也可以持续存在.

For longer-running tasks, particularly the sort where there will only be only one or a few, you probably want a Service instead, because those can persist even when your app's UI is shut down to save memory.

免责声明:我有一段时间没有编写 Android 代码了,所以这个答案可能已经过时,或者基于对事物工作原理的错误理解.如果有最近经验的人可以发表评论以确认,我将删除此警告;如果他们知道这是正确的,欢迎高级代表直接编辑这一段.

Disclaimer: I haven't done Android coding in awhile, so this answer may be out of date or based on a flawed understanding of how things work. I will remove this caveat if someone with more recent experience can comment to confirm; high-rep folks are welcome to just edit this paragraph away instead if they know this is correct.

这篇关于AsyncTask 超过几秒钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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