我正在编写一个应用程序,该应用程序使用ASI HTTP定期从Web服务器获取数据,然后处理该数据以在UI上显示与用户相关的内容。从单个服务器上的不同请求中检索数据。数据本身需要按特定顺序进行处理。数据块之一远大于其他数据块。

为了在处理数据时不锁定UI,我尝试使用NSOperationQueue在不同线程上运行数据处理。大约90%的时间都可以正常工作。但是,在剩余的10%的时间中,最大的数据块正在主线程上处理,这将导致UI阻塞1-2秒。该应用程序在不同的选项卡中包含两个MKMapViews。当同时加载两个MKMapViews选项卡时,在主线程上处理最大数据块的时间百分比增加到50%以上(这似乎是在有更多并发 Activity 时才会发生这种情况)。

有没有一种方法可以防止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 <operation x> on Main thread");
}

UI每次冻结时都会打印该行。这表明整个操作都在主线程上运行。实际上,通常是在主线程上运行的hugeDataProcessorOp。我认为这是因为操作总是总是从服务器最后接收到它的答案。

最佳答案

经过对自己的代码的大量研究,我可以确认这是一个编码错误。

剩下一个旧的调用,它没有经过NSInvocationOperation而是正在调用NSInvocationOperation应该直接调用的选择器(因此不使用并发的NSOperationQueue

这意味着NSOperationQueue不使用主线程(除非它是+mainQueue检索到的线程)。

10-07 19:55
查看更多