Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask Threading Rule - Can it really only be used once?

In the documentation on AsyncTask it gives the following as a rule related to threading:

  • The task can be executed only once (an exception will be thrown if a second execution is attempted.)

All this means is that you have to create a new instance of the class every time you want to use it, right? In other words, it must be done like this:

new DownloadFilesTask().execute(url1, url2, url3); new DownloadFilesTask().execute(url4, url5, url6); 

Or conversely, you can NOT do the following:

DownloadFilesTask dfTask = new DownloadFilesTask(); dfTask.execute(url1, url2, url3); dfTask.execute(url4, url5, url6); 

Can someone verify this is an accurate interpretation?

I realize I pretty much just answered this for myself as I was typing this out... But it wasn't immediately obvious to me so I think this would be useful to have posted nonetheless.

like image 864
stormin986 Avatar asked Apr 26 '10 04:04

stormin986


People also ask

What happen if we call execute more than once in AsyncTask?

Limitation Of AsyncTask There is a limit of how many tasks can be run simultaneously. Since AsyncTask uses a thread pool executor with max number of worker threads (128) and the delayed tasks queue has fixed size 10. If you try to execute more than 138 AsyncTasks the app will crash with java.

What are the problems in AsyncTask?

In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.

What happens to AsyncTask if activity is destroyed?

If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.

Is it possible to start AsyncTask from background thread?

Methods of AsyncTaskwe can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods . doInBackground(Params) − In this method we have to do background operation on background thread.


1 Answers

Can someone verify this is an accurate interpretation?

That is a very accurate interpretation.

like image 63
CommonsWare Avatar answered Sep 18 '22 06:09

CommonsWare