parallel execution of AsyncTask

2020-04-30 18:10发布

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.

2条回答
混吃等死
2楼-- · 2020-04-30 18:19

You can store reference to AsyncTask in member variable. So your code would look like this:

List<RSSItem> list = new Vector<RSSItem>();
DownloadFilesTask downloadTask = null;

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);

        if(downloadTask == null){
           downloadTask = new DownloadFilesTask();
           downloadTask.execute(rssFeedURL[currentCategory]);
        } else { 
           //show warning here
        }
    }
}

Of course, you'll need to set downloadTask to null in onPostExecute() for this to work.


As an added benefit you now can cancel outstanding task if Activity is being destroyed:

 @Override
 onDestroy() {
     if(downloadTask != null) {
         downloadTask.cancel();
     }
 }

Which you should do anyway.

查看更多
Animai°情兽
3楼-- · 2020-04-30 18:31

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:

task1.execute();
task2.execute();

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:

task.getStatus()==Status.FINISHED

in your case if you don't want to queue multiple tasks until the currently running one is complete then do something like this:

if(task==null || task.getStatus()!=Status.FINISHED){
    task = new DownloadFilesTask();
    task.execute();
}

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.

查看更多
登录 后发表回答