我正在编写一个应用程序,它定期使用ASI HTTP从Web服务器获取数据,然后处理该数据以在UI上显示与用户相关的内容.在单个服务器上从不同请求中检索数据.数据本身需要按特定顺序处理.其中一个数据块比其他数据块大得多.
为了在处理数据时不锁定UI,我尝试使用NSOperationQueue在不同的线程上运行数据处理.大约90%的时间都可以正常工作.但是,在剩余的10%的时间内,主线程上正在处理最大的数据块,这会导致UI阻塞1-2秒.该应用程序在不同的选项卡中包含两个MKMapView.当加载两个MKMapViews选项卡时,主线程上处理的最大数据块的时间百分比增加到50%以上(这似乎表明当存在更多并发活动时会发生这种情况).
有没有办法阻止NSOperationQueue在主线程上运行代码?
我试图使用NSOperationQueue -setMaxConcurrentOperationCount:,增加和减少它,但问题没有真正的变化.
这是启动定期刷新的代码:
- (void)refreshAll{
// Create Operations
ServerRefreshOperation * smallDataProcessor1Op = [[ServerRefreshOperation alloc] initWithDelegate:_smallDataProcessor1];
ServerRefreshOperation * smallDataProcessor2Op = [[ServerRefreshOperation alloc] initWithDelegate:_smallDataProcessor2];
ServerRefreshOperation * smallDataProcessor3Op = [[ServerRefreshOperation alloc] initWithDelegate:_smallDataProcessor3];
ServerRefreshOperation * smallDataProcessor4Op = [[ServerRefreshOperation alloc] initWithDelegate:_smallDataProcessor4];
ServerRefreshOperation * smallDataProcessor5Op = [[ServerRefreshOperation alloc] initWithDelegate:_smallDataProcessor5];
ServerRefreshOperation * hugeDataProcessorOp = [[ServerRefreshOperation alloc] initWithDelegate:_hugeDataProcessor];
// Create dependency graph (for response processing)
[HugeDataProcessorOp addDependency:smallDataProcessor4Op.operation];
[smallDataProcessor5Op addDependency:smallDataProcessor4Op.operation];
[smallDataProcessor4Op addDependency:smallDataProcessor3Op.operation];
[smallDataProcessor4Op addDependency:smallDataProcessor2Op.operation];
[smallDataProcessor4Op addDependency:smallDataProcessor1Op.operation];
// Start be sending all requests to server (startAsynchronous directly calls the ASIHTTPRequest startAsynchronous method)
[smallDataProcessor1Op startAsynchronous];
[smallDataProcessor2Op startAsynchronous];
[smallDataProcessor3Op startAsynchronous];
[smallDataProcessor4Op startAsynchronous];
[smallDataProcessor5Op startAsynchronous];
[hugeDataProcessorOp startAsynchronous];
}
这是设置启动数据处理的ASI HTTP完成块的代码:
[_request setCompletionBlock:^{
[self.delegate setResponseString:_request.responseString];
[[MyModel queue] addOperation:operation]; // operation is a NSInvocationOperation that calls the delegate parse method
}];
我在入口点的所有NSInvocationOperation Invoked方法中添加了这段代码:
if([NSThread isMainThread]){
NSLog(@"****************************Running on Main thread");
}
每次UI冻结时都会打印该行.这表明整个操作是在主线程上运行的.它实际上总是在主线程上运行的hugeDataProcessorOp.我认为这是因为它始终是从服务器接收其答案的操作.