2

我正在尝试使用后台线程在 iPad 上进行一些计算。问题是即使您正在运行计算。UI 在它们运行时被阻止......我做错了什么。

[mc evaluateFormula:adapted runNo:10000];

这是从 IBAction 调用的。

这是被调用的代码:

-(void)evaluateFormula:(NSDictionary *)frm runNo:(NSUInteger)runCount
{

    self.runCount = runCount;
    self.frm = frm;
    [self performSelectorInBackground:@selector(backgroundEvalFrm) withObject:nil];

//    for (int i = 0; i < runCount; i++) {
//        [self runFormula:frm];
//    }
//    

}

-(void)backgroundEvalFrm
{
    percentVal = self.runCount / 100;
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:20];



    for (int i = 0; i<self.runCount; i++) {
        NSInvocationOperation *op =[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(runFormula:) object:self.frm];
        [queue addOperation:op];

    }

}

那么为什么 UI 会被阻止呢?

这是线程返回码...它们都在同一个类中

-(void)runFormula:(NSDictionary *)frm
{
    NSMutableString *formula = [[frm objectForKey:kFormulaExpresion] mutableCopy];
    NSArray *variables = [frm objectForKey:kVariableArray];
    NSArray *evals = [self evaluateVariables:variables];


       for (NSDictionary *var in evals) {
           NSString *sym = [var objectForKey:kVariableSymbol];
           [formula replaceOccurrencesOfString:sym withString:[[var objectForKey:@"numVal"] stringValue] options:NSCaseInsensitiveSearch range:NSMakeRange(0, [formula length])];
    }
    //parse formula
    //NSLog(@"formula to parse:%@",formula);
    NSNumber *resNo = [formula numberByEvaluatingString];
    // NSLog(@"formula %@ the result : %f",formula,[resNo doubleValue]);
    //NSNumber *resNo = [NSNumber numberWithDouble:result];
    [self performSelectorOnMainThread:@selector(addNewResult:) withObject:resNo waitUntilDone:NO];
}

#pragma mark -- data aggregation delegate
-(void)addNewResult:(NSNumber *)nr
{
     NSLog(@"index : %i result: %f",currentIndex,[nr doubleValue]);
    [[self delegate] didReceiveResult:nr];
    resultsArray[currentIndex]=[nr doubleValue];
    currentIndex ++;
    if (  (currentIndex % percentVal) == 0) {
        [[self delegate] percentCompleted];
    }
}
4

1 回答 1

1

如果您的计算都以不协调的方式(很可能)竞争相同的资源(即 CPU 或 I/O),那么您应该显着降低最大并发操作数 - 尝试 2。很可能,它们将使用更少的资源完成时间/精力。此外,在执行计算期间,主线程不会减少到 CPU 时间的 5% 以下(结果:UI 响应更快)。

于 2013-02-22T11:43:54.627 回答