我正在阅读章节 processing bitmaps off the UI thread在安卓培训中。 在本章中,作者讨论了与 AsyncTask 结合使用时 GridView 的并发处理:
Common view components such as ListView and GridView introduce another issue when used in conjunction with the AsyncTask as demonstrated in the previous section. In order to be efficient with memory, these components recycle child views as the user scrolls. If each child view triggers an AsyncTask, there is no guarantee that when it completes, the associated view has not already been recycled for use in another child view. Furthermore, there is no guarantee that the order in which asynchronous tasks are started is the order that they complete.
对于上面这段,我有两个问题:
(1) GridView 的 subview 是什么? 以下图为例,是否每一个grid都是一个child view?
(2) 我对“如果每个 subview 都触发一个 AsyncTask,则不能保证它完成时,关联的 View 尚未被回收用于另一个 subview ”感到困惑。 任何人都可以解释更多细节吗?比如grid[1,1]触发了一个AsyncTask,当AsyncTask结束的时候,为什么会出现问题?
最佳答案
是的,每个网格项都是一个子项
View
.AsyncTask 的主要目的正在处理脱离主线程的长时间运行的作业,因此 UI 不会挂起。在内部,一个
AsyncTask
使用 ThreadPoolExecutor用固定数量的线程来管理任务。所以即使你开火二十AsyncTask
s,一次只有少数几个会被执行。同时,由于每个AsyncTask
在它自己的线程中运行,它可能随时完成,具体取决于系统决定如何安排您的线程。所以真的不能保证任务会以相同的顺序完成。
在脱离主线程处理图片时,还需要考虑以下场景。
在AdapterView
s,我们回收 subview ,这样我们就不需要初始化新的 View
每次都是 View
在屏幕上滚动。所以在这种情况下会发生一个 child View
将触发 AsyncTask
当图像出现在屏幕上时获取图像。
但是在获取图像之前,用户继续滚动并且 View 滚出屏幕并再次出现在另一侧(因为我们正在回收 View )。现在,它触发另一个 AsyncTask
获取它应该显示的图像。同时,较早的AsyncTask
与此 View 关联完成并设置此 View
的图像,即使它不是图像的正确位置。
关于android - 与 AsyncTask 结合使用时处理 GridView 的并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16343840/