能在Android的AsyncTask doInBackground同步序列化执行任务?能在、任务、序列化、AsyncTask

2023-09-12 22:53:53 作者:眼泪也成诗

时有可能使 AsyncTask.doInBackground 同步 - 或者达到相同的结果以另一种方式

Is it possible to make AsyncTask.doInBackground synchronized - or achieve the same result in another way?

class SynchronizedTask extends AsyncTask {

    @Override
    protected synchronized Integer doInBackground(Object... params) {
        // do something that needs to be completed 
        // before another doInBackground can be called
    }
}

在我的情况下,任何 AsyncTask.execute() A previous一个人完成,然后才能开始,但我需要执行code在 doInBackground 后,才previous的任务已经完成了。

In my case, any AsyncTask.execute() can be started before a previous one has completed, but I need to execute the code in doInBackground only after the previous task has finished.

修改:由于正确地指出,只有同步工作的同一个对象实例上。 不幸的是,它是不可能创建一个的AsyncTask 和呼叫执行()不止一次同一个对象实例,作为的AsyncTask 的文档。

EDIT: As correctly pointed out, the synchronization works only on the same object instance. Unfortunately, it is not possible to create an AsyncTask and call execute() more than once on the same object instance, as specified in the "Threading rules" section of the AsyncTask documentation.

解决方案是使用自定义执行人连载的任务,或者,如果你使用的API 11或以上, AsyncTask.executeOnExecutor() ,如在下面的意见建议。

The solution is to use a custom Executor to serialize the tasks, or, if you use API 11 or above, AsyncTask.executeOnExecutor(), as suggested in the comments below.

我发布an回答的示出的实施方案一 SerialExecutor 可用于排队将要顺序执行的任务。

I posted an answer showing an implementation of a SerialExecutor that can be used to queue tasks that will be executed sequentially.

推荐答案

在理想情况下,我想能够使用 AsyncTask.executeOnExecutor() SERIAL_EXECUTOR ,但这只是用对于API级别11或以上:

Ideally, I'd like to be able to use AsyncTask.executeOnExecutor() with a SERIAL_EXECUTOR, but this is only available for API level 11 or above:

new AsyncTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, params);

要针对低于11级了Android的API,我最终实现它封装了的的ExecutorService =nofollow的>

 
精彩推荐
图片推荐