AsyncTask的不足(待续)

下文来自:

http://foo.jasonhudgins.com/2010/05/limitations-of-asynctask.html

=============================================================

English 原文:

AsyncTask is a fine API, it's been said that it "holds your hand", and makes performing background operations painless. It pulls this off so well in fact, that I see people overusing it in situations where it's not really appropriate.

It's particularly unsuited for situations when you have a multiple tasks to perform concurrently. Imagine an Activity that needs to download about 30 small images from a remote server, and update the UI as these become available. AsyncTask uses a static internal work queue with a hard-coded limit of 10 elements. That means if you were to create an AsyncTask instance for each image, the work queue would quickly overflow and many of your tasks would get rejected. The best solution in this case is to create your own ThreadPoolExecutor instance that uses a queue that's large enough to hold all your tasks, if you need an unbounded queue, a LinkedBlockingQueue will work just fine.

Another severe limitation is that an AsyncTask can't survive your Activity being torn down and recreated on the other side.  Even if you pass it to the new instance via onRetainNonConfigurationState, the internal Handler inside the AsyncTask is still going to be stale and it's not going to behave correctly.  This is important to consider, and the Android documentation makes no mention of it all.  I've already blogged this scenario in detail, so I won't flog a dead horse here.

There are a few other minor issues, such as the fact thatyou can't change the background threads execution priority. It's hard-coded to a low priority, which granted, is the sensible default.  Also, exception handling is not very well supported.

So just to reiterate, AsyncTask is a nice API, but you should understand it's limitations and apply it appropriately.  If you're serious about writing mobile apps, then you're going to need a few more tools in the toolbox to get the job done.


中文翻译:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值