Asynchronous request to the server from background thread

前端 未结 3 1172
北海茫月
北海茫月 2020-12-04 07:01

I\'ve got the problem when I tried to do asynchronous requests to server from background thread. I\'ve never got results of those requests. Simple example which shows the pr

3条回答
  •  天命终不由人
    2020-12-04 07:57

    Yes, the thread is exiting. You can see this by adding:

    -(void)threadDone:(NSNotification*)arg
    {
        NSLog(@"Thread exiting");
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(threadDone:)
                                                 name:NSThreadWillExitNotification
                                               object:nil];
    

    You can keep the thread from exiting with:

    -(void) downloadImage
    {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        [self downloadImage:urlString];
    
        CFRunLoopRun(); // Avoid thread exiting
        [pool release];
    }
    

    However, this means the thread will never exit. So you need to stop it when you're done.

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        CFRunLoopStop(CFRunLoopGetCurrent());
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        CFRunLoopStop(CFRunLoopGetCurrent());
    }
    

    Learn more about Run Loops in the Threading Guide and RunLoop Reference.

提交回复
热议问题