两个不同的AsyncTasks同时执行 [英] Two different AsyncTasks execute at the same time
问题描述
我总共有两种不同的AsyncTask
实现,比如说AT1
和AT2
.
I have two total different implementations of AsyncTask
, lets say AT1
and AT2
.
AT1
,然后执行AT2
. AT1
在doInBackground
中等待,直到AT2
通过每500 ms轮询一次此数据来完成其任务.但这永远不会发生.
AT1
is executed first, then AT2
is executed. AT1
waits in doInBackground
until AT2
has done its task by polling this data every 500 ms. But this never happens.
所以我基本上想要的是:
So what I basically want is this:
但是似乎发生了什么:
除了AT1
从未完成,并且AT2
从未启动.
But what seems to happen is this:
Except AT1
is never done, and AT2
is never started.
有没有办法强制这两个AsyncTask
在两个单独的线程上执行,或者有其他解决方案吗?
Is there a way I can force these two AsyncTask
s to be executed on two seperate threads, or is there another solution for this?
不可能首先启动AT2
,然后再执行AT1
.
It is not possible to first start AT2
and after that execute AT1
.
编辑
为了澄清起见:AT1
是在用户打开特定屏幕并需要根据位置下载该屏幕的数据时执行的. AT2
在位置更改时执行,并且发生这种情况时,会进行一些无法在UI线程上执行的计算.
EDIT
For clarification: AT1
is executed when a user opens a particular screen, and needs to download data for that screen, based on a location. AT2
is executed on Location change, and when that happens, some calculations are made that cannot be done on the UI thread.
当从未执行过AT2
时,AT1
没有下载数据的位置,因此需要等待AT2
完成.执行AT2
后,位置数据已经存在,并且AT1
无需等待.
When AT2
has never been executed, AT1
has no location to download data for, so it needs to wait for AT2
to finish. When AT2
has been executed, the location data is already there, and AT1
doesn't need to wait.
此外,此问题发生在ICS中,而不是在Android 2.3中发生,例如
Also, this problem occurs in ICS, not in Android 2.3, like this answer suggests.
推荐答案
When I posted this question, this question appeared in the Related
section.
It advices to use executeOnExecutor
, I've implemented this as follows:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new SetLocationAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, location);
} else {
new SetLocationAsyncTask().execute(location);
}
这篇关于两个不同的AsyncTasks同时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!