Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does AsyncTask's execute() must be invoked on the UI thread even though AsyncTask uses Looper.getMainLooper() in internalHandler?

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.

like image 581
Sharad Avatar asked Mar 15 '17 09:03

Sharad


1 Answers

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?

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.

like image 138
nandsito Avatar answered Oct 14 '22 04:10

nandsito