【问题标题】:Whats the point of having an async task when get() waits for it to complete当 get() 等待它完成时有一个异步任务有什么意义
【发布时间】:2014-04-04 02:10:54
【问题描述】:

我正在使用下面的代码从 Asynctask 获取结果

Ui thread
.....
....
    int result = new MyCustomTask().execute().get();

    if (result == 1) {
    }
    else {
    }
----
----

但我的疑问是“当 get() 等待它完成时,有一个异步任务有什么意义”

【问题讨论】:

    标签: android performance android-asynctask


    【解决方案1】:

    打电话给get()没有意义。

    只要有

    new MyCustomTask().execute();
    

    调用get() 会阻塞等待结果的ui 线程。这使得 AsyncTask 不再是异步的。

    doInbackground 计算的结果是onPostExecute 的参数。因此您可以在doInbackground 中重新运行结果并在onPostExecute 中更新ui。

    如果是 Activity 的内部类,您可以使用onPostExecute() 更新 ui,或者您可以使用接口作为 Activity 的回调来获取结果。

    使用接口作为回调

    How do I return a boolean from AsyncTask?

    【讨论】:

    • 是的..为此在 onPostExecute() 中写入您的条件,这样就不会阻塞 UI 线程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多