开发者

AsyncTask Threading Rule - Can it really only be used once?

开发者 https://www.devze.com 2022-12-28 16:41 出处:网络
In the documentation on AsyncTask it gives the following as a rule related to threading: The task can be executed only once (an exception will be thrown if a second exec开发者_如何学Goution is atte

In the documentation on AsyncTask it gives the following as a rule related to threading:

  • The task can be executed only once (an exception will be thrown if a second exec开发者_如何学Goution is attempted.)

All this means is that you have to create a new instance of the class every time you want to use it, right? In other words, it must be done like this:

new DownloadFilesTask().execute(url1, url2, url3);
new DownloadFilesTask().execute(url4, url5, url6);

Or conversely, you can NOT do the following:

DownloadFilesTask dfTask = new DownloadFilesTask();
dfTask.execute(url1, url2, url3);
dfTask.execute(url4, url5, url6);

Can someone verify this is an accurate interpretation?

I realize I pretty much just answered this for myself as I was typing this out... But it wasn't immediately obvious to me so I think this would be useful to have posted nonetheless.


Can someone verify this is an accurate interpretation?

That is a very accurate interpretation.


There is one more gotcha with AsyncTasks. Please note that in the example

new DownloadFilesTask().execute(url1, url2, url3);
new DownloadFilesTask().execute(url4, url5, url6);

executed on Android 3+ (API level 11, HONEYCOMB) url1 and url4 will not be downloaded in parallel. In particular, if contacting url1 is going to time out, the transfer on url4 will not even start until it times out. Unless you explicitly specify otherwise, all AsyncTasks are serviced by the same single worker thread.

The docs say:

Order of execution

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

0

精彩评论

暂无评论...
验证码 换一张
取 消