让ASIHTTPRequest不占用主线程
2011 8 5 07:49 PM 7173次查看
分类:iOS开发 标签:Objective-C, iOS开发
不过使用中我发现,当下载线程数超过2时,就会影响到主线程响应用户请求的速度了。好奇之余我测试了一下completionBlock,发现它总是在主线程调用,而NSOperation的文档中却说一般会在子线程中执行。
于是看了下ASIHTTPRequest.m,终于发现问题所在了:
// Subclasses might override this method to process the result in the same thread
// If you do this, don't forget to call [super requestFinished] to let the queue / delegate know we're done
- (void)requestFinished
{
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
NSLog(@"[STATUS] Request finished: %@",self);
#endif
if ([self error] || [self mainRequest]) {
return;
}
if ([self isPACFileRequest]) {
[self reportFinished];
} else {
[self performSelectorOnMainThread:@selector(reportFinished) withObject:nil waitUntilDone:[NSThread isMainThread]];
}
}
这段代码显示了,在不使用自动代理脚本时,就会在主线程执行reportFinished。解决的办法很简单,可以按它所说的继承ASIHTTPRequest,并改写requestFinished方法。或者像我这种懒人,直接改源码:
- (void)requestFinished
{
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
NSLog(@"[STATUS] Request finished: %@",self);
#endif
if ([self error] || [self mainRequest]) {
return;
}
[self reportFinished];
}
改完后重新构建一遍,发现至少5个下载线程时也不会影响主线程了,搞定收工~
向下滚动可载入更多评论,或者点这里禁止自动加载。