parallel execution of AsyncTask

后端 未结 2 1070
南方客
南方客 2021-01-28 11:14

An AsyncTask is executed on click:

List list = new Vector();
private OnClickListener click = new OnClickL         


        
相关标签:
2条回答
  • 2021-01-28 11:57

    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.

    0 讨论(0)
  • 2021-01-28 11:58

    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.

    0 讨论(0)
提交回复
热议问题