From f0ce3a86e3b27310cfcebc6eec9802a9b44128d7 Mon Sep 17 00:00:00 2001 From: Erik Olsson Date: Thu, 23 Feb 2012 18:05:27 +0100 Subject: [PATCH] Proposed fix to the race condition that occurs when stressing AFURLConnectionOperation. Cancels the NSURLConnection on the same thread as the one where it was created. --- AFNetworking/AFURLConnectionOperation.m | 28 ++++++++++++++----------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 192c3dc..b39e574 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -334,21 +334,25 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat self.state = AFHTTPOperationFinishedState; } +-(void)cancelConnection { + [self willChangeValueForKey:@"isCancelled"]; + _cancelled = YES; + + if (self.connection) { + [self.connection cancel]; + //We must send this delegate protcol message ourselves since the above [self.connection cancel] causes the connection to never send another message to its delegate. + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; + [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]]; + } + + [self didChangeValueForKey:@"isCancelled"]; +} + - (void)cancel { [self.lock lock]; if (![self isFinished] && ![self isCancelled]) { - [super cancel]; - - [self willChangeValueForKey:@"isCancelled"]; - _cancelled = YES; - if (self.connection) { - [self.connection cancel]; - - // We must send this delegate protcol message ourselves since the above [self.connection cancel] causes the connection to never send another message to its delegate. - NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]]; - } - [self didChangeValueForKey:@"isCancelled"]; + [super cancel]; + [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; } [self.lock unlock]; }