AsyncTask与Activity.runOnUiThread()与Handler.post() [英] AsyncTask vs Activity.runOnUiThread() vs Handler.post()
问题描述
我正在研究大型应用程序的代码. UI中使用了3种异步模式,它们似乎都是等效的:
I'm studying the code of a large app. There are 3 asynchrony patterns used in the UI, all of them seem equivalent:
模式1,AsyncTask
new AsyncTask<X, Void, Z>() {
protected Boolean doInBackground(X... params) {
//background task
}
protected void onPostExecute(Z res) {
//UI callback
}
}.execute();
模式2,Activity.runOnUiThread(Runnable)
new Thread() {
public void run() {
//background task
runOnUiThread(new Runnable() {
public void run() {
//UI callback
}
});
}
}.start();
模式3,Handler.post(可运行)
new Thread() {
public void run() {
//background task
handler.post(new Runnable() {
public void run() {
//UI callback
}
});
}
}.start();
问题:
- 我缺少的3种模式之间有何区别? (除了AsyncTask在具有后台优先级的预先存在的线程池上运行.)
- 在任何情况下都倾向于使用特定模式?
推荐答案
无论是可见的还是内部的,它们实际上都是Handler
.
They are all really a Handler
either visibly or internally.
AsyncTask#finish()
是从Handler
消息循环中调用的.
AsyncTask#finish()
that calls onPostExecute()
is called from a Handler
message loop.
runOnUiThread()
将Runnable
发布到Handler
.如果它是UI线程,则可运行对象将同步执行-这并不总是可取的.
runOnUiThread()
posts the Runnable
to a Handler
if the current thread is not the UI thread. If it is the UI thread, the runnable is executed synchronously - this is not always desirable.
直接使用Handler
可以为您提供低级控制,并且仅此一个.
Directly using a Handler
gives you low level control and only that.
使用什么取决于您的特定要求.
What to use depends on your specific requirements.
这篇关于AsyncTask与Activity.runOnUiThread()与Handler.post()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!