用于网络请求的 AsyncTask 与 ThreadPoolExecutor
我正在开发一个项目,我需要点击 Web 服务下载 JSON 数据并将其表示在列表中。所有列表项都有缩略图 URL,可以下载并显示在列表项中。
我已经使用 ThreadPoolExecutor 和 AsyncTask 完成了整个调用部分。
但从设计的角度来看,这是一个更好的选择:
1.ThreadPoolExecutor
2. AsyncTask
一些建议。 ThreadPoolExecutor的:
1. 用户可以定义编号。可以执行的并发线程数。
2. 一次性取消所有请求。
几个adv。 AsyncTask 的:
1.它内部使用ThreadPoolExecutor,但是我们不能定义no。同时运行的线程数。
2. 取消单个请求很容易。
3. 能够附加和分离任务。
4. 从 doInBackground 更新 UI 很简单。
我知道 AsyncTask 的更多优点,但是对于简单的应用程序,例如从 Web 服务获取数据,然后再获取图像。
AsyncTask 或 ThreadPoolExecutor 哪个更合适?如果您能提供一些有关您选择的理由,那将会很有帮助。
我在这里读过一些关于 SO 的文章,但没有一篇文章对两者进行比较。如果我错过了任何内容,抱歉给您带来麻烦,请您给我发布相同内容的链接。
提前致谢。
I am working on a project where i need to hit a web service download the data which is JSON and will be represented in a list. And all the list items have there thumbnail url's which would be downloaded and displayed in the list item.
I have done the entire calling part with both a ThreadPoolExecutor and a AsyncTask.
But from a design perspective which is a better option out of:
1. ThreadPoolExecutor
2. AsyncTask
Few adv. of ThreadPoolExecutor:
1. User can define no. of concurrent threads that can be executed.
2. Cancelling all the request at once.
Few adv. of AsyncTask:
1. Internally it uses a ThreadPoolExecutor, however we cant define no. of threads that run simultaneously.
2. Cancelling a single request is easy.
3. Ability to attach and detach a task.
4. Updating the UI from doInBackground is simple.
I know more advantages of AsyncTask, however for a simple application like fetching data from a web service and later on fetching images.
Which would be more appropriate a AsyncTask or ThreadPoolExecutor? If you can provide a few reasons regarding your choice it would be helpful.
I have read a few article here on SO but none that compares the two. If there are any that i missed sorry for the trouble could you please post me the link for the same.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为如果您想使用一系列“级联调用”加载缩略图,AsyncTask 很有用:在 onPostExecute 中,您可以启动下一个 AsyncTask 来下载下一个缩略图。
但如果你想提高效率,我建议使用ThreadPoolExecutor。这是来自 developer.android.com 的一句话:
总之,ThreadPoolExecutor 可能是为像您这样的情况而设计的;因此,我向您推荐这门课。
I consider that AsyncTask is useful if you want to load thumbnail using a series "cascade-call": in the onPostExecute, you can start the next AsyncTask to download the next thumbnail.
But if you want to improve efficiency, I suggest using ThreadPoolExecutor. This is a sentence from developer.android.com:
In conclusion, ThreadPoolExecutor was probably designed for cases such as your; for this reason, I suggest you this class.