0

I want to know if there are any consequences to starting an AsyncTask in another AsyncTask's doInBackground() method. I've read that it's not recommended, but I'm not seeing any consequences thus far.

I've started AsyncTask A like so:

asyncTaskA.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)

then I initiate AsyncTask B from AsyncTask A's doInBackground() method like so:

protected Void doInBackground(Void...params){
asyncTaskB.execute();
}

Based on what I've seen so far, The onPostExecute() method of AsyncTask B still ends up in the main UI thread as expected. I also believe that even if AsyncTask A dies (the parent task) AsyncTask B will continue.

I've heard that executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) enables parallel execution, but I'm not 100% sure what that means code wise. Does it specifically enable the functionality that I'm seeing? AKA, the ability to execute nested async tasks from the doInBackground() method of the task itself.

Thanks.

jtompkj
  • 93
  • 2
  • 8
  • This should answer your question: [enter link description here](https://stackoverflow.com/questions/19520668/start-asynctask-from-another-asynctask-doinbackground) – Maddin Dec 19 '18 at 00:32
  • [This should answer your question](https://stackoverflow.com/questions/19520668/start-asynctask-from-another-asynctask-doinbackground) – Maddin Dec 19 '18 at 00:35
  • 1
    @Maddin Yeah I read that one, it seems conflicting with no solid answer. The most up voted is saying don't do it, but the lower voted ones that mention the Executor say it's possible however there's no example with it really. I don't seem to have the need to start the nested AsyncTask from the main ui thread, it starts fine from the background thread. – jtompkj Dec 19 '18 at 00:48
  • I've found I can even execute an AsyncTask from an AsyncTask's doInBackground() without .executeOnExecutor just using .execute(), even though https://developer.android.com/reference/android/os/AsyncTask specifically states .execute() can only be called from the UI thread... – jtompkj Dec 19 '18 at 04:16
  • Just having to create an AsyncTask from within an AsyncTask sounds like bad design. In addition, AsyncTask is for the small tasks all running on one thread. The way you describe, you will be much more robust just creating your own Thread and Handler. – lionscribe Dec 19 '18 at 06:06
  • @lionscribe I agree it's bad design. But I want to know if it's bad design because it will crash, or if it's bad design because it's just not intended. – jtompkj Dec 19 '18 at 23:29

0 Answers0