AsyncTask的并行执行
单击时执行 AsyncTask:
List<RSSItem> list = new Vector<RSSItem>();
private OnClickListener click = new OnClickListener() {
public void onClick(View view) {
list.clear();
if((dft.getStatus().toString()).equals("RUNNING")) dft.cancel(true);
currentCategory = catigoriesHolder.indexOfChild(view);
dft = new DownloadFilesTask();
dft.execute(rssFeedURL[currentCategory]);
}
};
在 doInBackGround 方法中,变量 list 已满。如何防止列表在用于填充 ListView 时被清除。如何确定在下次单击时,AsyncTask 的前一个实例已被销毁,并且不再对其进行进一步处理。
该问题与 1.6 版本有关。
An AsyncTask is executed on click:
List<RSSItem> list = new Vector<RSSItem>();
private OnClickListener click = new OnClickListener() {
public void onClick(View view) {
list.clear();
if((dft.getStatus().toString()).equals("RUNNING")) dft.cancel(true);
currentCategory = catigoriesHolder.indexOfChild(view);
dft = new DownloadFilesTask();
dft.execute(rssFeedURL[currentCategory]);
}
};
In doInBackGround method the variable list is filled up. How to prevent the list to be cleared at point at which it is used to fill ListView. How to be sure, that on next click the previous instance of AsyncTask have been destroyed and there is no further processing of it.
The issue is regarding version 1.6.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先异步任务通常不会同时运行,但同一个异步任务的执行实际上是一个队列。所以想象一下,如果您创建 DownloadFilesTask 的 2 个实例并在相同的方法如下:
这意味着任务 2 在任务 1 完成整个 onPreExecute、DoInBg、onPostExecute 过程之前不会运行,因此您可以确定这不会同时发生。 taskStatus 也是一个 ENUM。您可以检查它,而不是像这样的字符串:
在您的情况下,如果您不想将多个任务排队直到当前正在运行的任务完成,则执行如下操作:
取消任务意味着 doInBackground 将运行,但 postExecute 不会运行。您可以检查任务是否正在运行,以便在 bg 处理期间也取消它。
First of all async task's in general don't run at the same moment, but the execution of the same async task is actually a queue. so imagine if you create 2 instances of your DownloadFilesTask and execute them in the same method like:
this means that task 2 wont be run until task1 has finished the whole onPreExecute,DoInBg,onPostExecute process so you can be sure that that won't happen simultaniously. also the taskStatus is an ENUM. you can check it as such not as a string like:
in your case if you don't want to queue multiple tasks until the currently running one is complete then do something like this:
Canceling a task means that the doInBackground will run but postExecute wont. you can check if the task isRunning in order to cancel it during bg processing somewhere also.
您可以在成员变量中存储对 AsyncTask 的引用。因此,您的代码将如下所示:
当然,您需要在
onPostExecute()
中将downloadTask
设置为null
才能正常工作。作为一个额外的好处,如果活动被破坏,您现在可以取消未完成的任务:
无论如何您都应该这样做。
You can store reference to
AsyncTask
in member variable. So your code would look like this:Of course, you'll need to set
downloadTask
tonull
inonPostExecute()
for this to work.As an added benefit you now can cancel outstanding task if Activity is being destroyed:
Which you should do anyway.