Wait for multiple AsyncTask to complete

前端 未结 5 1032
自闭症患者
自闭症患者 2020-12-15 21:16

I am parallelizing my operation by splitting it in the exact number of cores available and then, by start the same number of AsyncTask, performing the same operation but on

5条回答
  •  悲哀的现实
    2020-12-15 21:56

    First, add this class to your project

    public abstract class MultiTaskHandler {
        private int mTasksLeft;
        private boolean mIsCanceled = false;
    
        public MultiTaskHandler(int numOfTasks) {
            mTasksLeft = numOfTasks;
        }
    
        protected abstract void onAllTasksCompleted();
    
        public void taskComplete()  {
            mTasksLeft--;
            if (mTasksLeft==0 && !mIsCanceled) {
                onAllTasksCompleted();
            }
        }
    
        public void reset(int numOfTasks) {
            mTasksLeft = numOfTasks;
            mIsCanceled=false;
        }
    
        public void cancel() {
            mIsCanceled = true;
        }
    }
    

    Then:

    int totalNumOfTasks = 2; //change this to the number of tasks that you are running
    final MultiTaskHandler multiTaskHandler = new MultiTaskHandler(totalNumOfTasks) {
        @Override
        protected void onAllTasksCompleted() {
           //put the code that runs when all the tasks are complete here
        }
    };
    

    Then in each task - when completed, add the line: multiTaskHandler.taskComplete();

    Example:

    (new AsyncTask() {
    
        @Override
        protected Void doInBackground(Void... voids) {
            // do something...
            return null;
        }
    
        @Override
        protected void onPostExecute(Void aVoid) {
            multiTaskHandler.taskComplete();
        }
    }).execute();
    

    You can use multiTaskHandler.cancel() if you want to cancel the code that runs when all the tasks have completed. For instance - if you have an error (don't forget to also cancel all the other tasks).

    * This solution will not pause the main thread!

提交回复
热议问题