如何使主线程等待,当我不知道异步任务何时才能完成工作.? [英] How to make the Main thread wait, when i dont know when will Async task finish the job.?

查看:77
本文介绍了如何使主线程等待,当我不知道异步任务何时才能完成工作.?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Async任务解析包含一些名称的xml文件,并通过主线程再次将这些名称填充到listview中.但是在我的情况下发生的是,当Async任务仍在运行时,主线程已经在列表视图中填充了名称,这导致列表视图上没有任何项.我应该让主线程等到异步任务完成工作,还是有其他方法解决这个问题.如果是,当我不知道异步任务可能需要多长时间才能完成时,如何使主线程等待??

I am parsing the xml file containing some names using the Async task and populating these names to the listview again via the main thread. But whats happening in my case is, when the Async task is still running, the main thread is already populating the names to the listview which is resulting in no items on the listview. Should i make the main thread wait until the Async task finish the job or is there any other way to solve this prob.? if yes how can i make the main thread wait when i don't know that how long the Async task might take to finish.?

推荐答案

如果您使用过AsyncTask,请在doInBackground()中进行xml提取,并更新onPostExecute()中listview的所有UI元素,然后在主UI线程,并自动在doInBackground()之后.这样,您不必显式使UI线程等待

If you have used AsyncTask, then do the xml fetch in doInBackground() and update all your UI elements of the listview inside the onPostExecute(), this runs on the main UI thread and is automatically after doInBackground(). This way you dont have to explicitly make the UI thread wait

这篇关于如何使主线程等待,当我不知道异步任务何时才能完成工作.?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆