Why must the AsyncTask
's method execute(Params...)
invoked on the UI thread as stated in the documentation even though AsyncTask uses Looper.getMainLooper() in internalHandler?
I tried creating the task and calling its execute(Params...) from a background thread and it works fine.
Why must the
AsyncTask
's methodexecute(Params...)
invoked on the UI thread as stated in the documentation even though AsyncTask uses Looper.getMainLooper() in internalHandler?
Why can be a philosophical question sometimes... I inspected AsyncTask
code for Android API 25 and the code itself does not give us a straight answer. Only the person who developed this class knows why.
But, what the code do tell us is that it could forward calls from a background thread to the UI thread, but it doesn't. So the developer didn't have the expertise to do that, or was lazy, or wanted to enforce a pattern, or whatever.
I tried creating the task and calling its execute(Params...) from a background thread and it works fine.
Mind that it worked, but it's not guaranteed to always work. Multithreading programming is pretty tricky, and its debugging can be the hell on earth.
In the code inspection I noticed that the onPreExecute()
call is done in the same thread that invokes execute(Params...)
. So, if you call execute(Params...)
in a background thread, it will break the invariant that onPreExecute()
runs on UI thread.
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