In my app i have buttons, when clicked will query the database and show result on screen. The query action will normally take 1 ~ 3 sec. These buttons will be clicked very often.
I've implemented this action on both AsyncTask and Thread but see very little different.
However in the long term, especially when the buttons are clicked many times, which will be more beneficial, in terms of resources (CPU, memory) ?
AsyncTask : Response after process completion , Thread : process completion .
AsyncTask are similar, in fact, they make use of Handler , but doesn't run in the UI thread, so it's good for fetching data, for instance fetching web services. Later you can interact with the UI. Thread however can't interact with the UI, provide more "basic" threading and you miss all the abstractions of AsyncTask .
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
In newer Android versions, 5 threads are create by default, and the ThreadPoolExecutor will attempt to run the AsyncTask s on these 5 threads. If you create more than 5 AsyncTask s, it may either queue them or create new threads (but only up to 128).
When you use a Thread
, you have to update the result on the main thread using the runOnUiThread()
method, while an AsyncTask
has the onPostExecute()
method which automatically executes on the main thread after doInBackground()
returns.
While there is no significant difference between these two in terms of "which is more beneficial", I think that the AsyncTask
abstraction was devised so that a programmer doesn't have to synchronize the UI & worker threads. When using a Thread
, it may not always be as simple as calling runOnUiThread()
; it can get very tricky very fast. So if I were you, I'd stick to using AsyncTask
and keep Thread
for more specialized situations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With