ios并发会造成什么问题_iphone – 如何防止IOS并发NSOperation在主线程上运行

我正在编写一个应用程序,它定期使用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.我认为这是因为它始终是从服务器接收其答案的操作.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值