本文介绍了Android中的线程池,直接调用doinbackground的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我直接调用doInBackground,通过将其公开并用某些功能覆盖它,它的执行速度比我自己创建线程要快得多-这样做是不好的做法吗?

If I call doInBackground directly, by making it public and overwriting it with some functionality, it executes much faster than if I create a thread myself - is it bad practice to do that?

推荐答案

开发人员指南说:

请勿手动调用onPreExecute(),onPostExecute(Result),doInBackground(Params ...),onProgressUpdate(Progress ...).

Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.

因此,手动调用doInBackground(Params)确实是一个坏习惯.

So it is indeed bad practice to call doInBackground(Params) manually.

以下是一些规则:

必须在UI线程上加载AsyncTask类.自Build.VERSION_CODES.JELLY_BEAN起自动完成.

The AsyncTask class must be loaded on the UI thread. This is done automatically as of Build.VERSION_CODES.JELLY_BEAN.

必须在UI线程上创建任务实例.

The task instance must be created on the UI thread.

execute(Params ...)必须在UI线程上调用.

execute(Params...) must be invoked on the UI thread.

请勿手动调用onPreExecute(),onPostExecute(Result),doInBackground(Params ...),onProgressUpdate(Progress ...).

Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.

该任务只能执行一次(如果尝试第二次执行,则会抛出异常.)

The task can be executed only once (an exception will be thrown if a second execution is attempted.)

不幸的是,没有清晰的文档说明为什么不应该手动调用任何方法,但是主要原因可能是,如果您手动调用doInBackground(),则代码可能会在您的主线程而不是后台线程中执行.

Unfortunately there is no clear documentation why you should not call any method manually but the main reason might be that if you call doInBackground() manually your code could get executed in you main thread instead of a background thread.

...这样做不好吗?

...is it bad practice to do that?

答案:是的!

这篇关于Android中的线程池,直接调用doinbackground的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-01 01:24