5

我有一个 NSOperationQueue ,它包含 2 个 NSOperations 并设置为通过设置setMaxConcurrentOperationCount为 1 一个接一个地执行它们。

其中一个操作是标准的非并发操作(只是一个main方法),它同步地从 Web 检索一些数据(当然是在单独的操作线程上)。另一个操作是并发操作,因为我需要使用一些必须异步运行的代码。

问题是我发现并发操作只有在首先添加到队列时才有效。如果它发生在任何非并发操作之后,那么奇怪的是该start方法被调用得很好,但是在该方法结束并且我已经设置我的连接来回调一个方法之后,它永远不会这样做。之后不会执行队列中的进一步操作。就好像它在 start 方法返回后挂起,并且没有调用来自任何 url 连接的回调!

如果我的并发操作首先放在队列中,那么一切正常,异步回调工作,后续操作在完成后执行。我完全不明白!

你可以在下面看到我的并发 NSOperation 的测试代码,我很确定它是可靠的。

任何帮助将不胜感激!

主线程观察:

我刚刚发现,如果并发操作首先在队列上,那么该[start]方法将在主线程上调用。但是,如果它不是队列中的第一个(如果它在并发或非并发之后),[start]则不会在主线程上调用该方法。这似乎很重要,因为它符合我的问题的模式。这可能是什么原因?

并发 NSOperation 代码:

@interface ConcurrentOperation : NSOperation {
    BOOL executing;
    BOOL finished;
}
- (void)beginOperation;
- (void)completeOperation;
@end

@implementation ConcurrentOperation
- (void)beginOperation {
    @try {

        // Test async request
        NSURLRequest *r = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.google.com"]];
        NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:r delegate:self];
        [r release];

    } @catch(NSException * e) {
        // Do not rethrow exceptions.
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Finished loading... %@", connection);
    [self completeOperation];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Finished with error... %@", error);
    [self completeOperation]; 
}
- (void)dealloc {
    [super dealloc];
}
- (id)init {
    if (self = [super init]) {

        // Set Flags
        executing = NO;
        finished = NO;

    }
    return self;
}
- (void)start {

    // Main thread? This seems to be an important point
    NSLog(@"%@ on main thread", ([NSThread isMainThread] ? @"Is" : @"Not"));

    // Check for cancellation
    if ([self isCancelled]) {
        [self completeOperation];
        return;
    }

    // Executing
    [self willChangeValueForKey:@"isExecuting"];
    executing = YES;
    [self didChangeValueForKey:@"isExecuting"];

    // Begin
    [self beginOperation];

}

// Complete Operation and Mark as Finished
- (void)completeOperation {
    BOOL oldExecuting = executing;
    BOOL oldFinished = finished;
    if (oldExecuting) [self willChangeValueForKey:@"isExecuting"];
    if (!oldFinished) [self willChangeValueForKey:@"isFinished"];
    executing = NO;
    finished = YES;
    if (oldExecuting) [self didChangeValueForKey:@"isExecuting"];
    if (!oldFinished) [self didChangeValueForKey:@"isFinished"];
}

// Operation State
- (BOOL)isConcurrent { return YES; }
- (BOOL)isExecuting { return executing; }
- (BOOL)isFinished { return finished; }

@end

排队码

// Setup Queue
myQueue = [[NSOperationQueue alloc] init];
[myQueue setMaxConcurrentOperationCount:1];

// Non Concurrent Op
NonConcurrentOperation *op1 = [[NonConcurrentOperation alloc] init];
[myQueue addOperation:op1];
[op1 release];

// Concurrent Op
ConcurrentOperation *op2 = [[ConcurrentOperation alloc] init];
[myQueue addOperation:op2];
[op2 release];
4

3 回答 3

10

我发现了问题所在!

Dave Dribin 的这两篇无价的文章非常详细地描述了并发操作,以及 Snow Leopard 和 iPhone SDK 在异步调用需要运行循环的事物时引入的问题。

http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/ http://www.dribin.org/dave/blog/archives/2009/09/13/snowy_concurrent_operations/

也感谢 Chris Suter 为我指明了正确的方向!

关键是保证start我们在主线程上调用的方法:

- (void)start {

    if (![NSThread isMainThread]) { // Dave Dribin is a legend!
        [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
        return;
    }

    [self willChangeValueForKey:@"isExecuting"];
    _isExecuting = YES;
    [self didChangeValueForKey:@"isExecuting"];

    // Start asynchronous API

}
于 2009-10-29T13:37:39.413 回答
6

您的问题很可能与 NSURLConnection 有关。NSURLConnection 依赖于运行特定模式的运行循环(通常只是默认模式)。

您的问题有多种解决方案:

  1. 确保此操作仅在主线程上运行。如果您在 OS X 上执行此操作,您会想要检查它在所有运行循环模式(例如模式和事件跟踪模式)中是否符合您的要求,但我不知道 iPhone 上的情况如何。

  2. 创建和管理您自己的线程。不是一个好的解决方案。

  3. 调用 -[NSURLConnection scheduleInRunLoop:forMode:] 并传入主线程或您知道的另一个线程。如果你这样做,你可能想先调用 -[NSURLConnection unscheduleInRunLoop:forMode:] 否则你可能会在多个线程中接收数据(或者至少这是文档似乎建议的)。

  4. 使用 +[NSData dataWithContentsOfURL:options:error:] 之类的东西,这也将简化您的操作,因为您可以将其设为非并发操作。

  5. #4 的变体:使用 +[NSURLConnection sendSynchronousRequest:returningResponse:error:]。

如果你能侥幸逃脱,请执行 #4 或 #5。

于 2009-10-29T11:25:11.950 回答
0

我没有注意到,也没有看到任何提及addDependency:,这似乎是让操作以正确的顺序执行的先决条件。

简而言之,第二个操作依赖于第一个。

于 2009-10-29T09:54:57.980 回答