Asynchronous request to the server from background thread

前端 未结 3 1179
北海茫月
北海茫月 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:55

    NSURLRequests are completely asynchronous anyway. If you need to make an NSURLRequest from a thread other than the main thread, I think the best way to do this is just make the NSURLRequest from the main thread.

    // Code running on _not the main thread_:
    [self performSelectorOnMainThread:@selector( SomeSelectorThatMakesNSURLRequest ) 
          withObject:nil
          waitUntilDone:FALSE] ; // DON'T block this thread until the selector completes.
    

    All this does is shoot off the HTTP request from the main thread (so that it actually works and doesn't mysteriously disappear). The HTTP response will come back into the callbacks as usual.

    If you want to do this with GCD, you can just go

    // From NOT the main thread:
    dispatch_async( dispatch_get_main_queue(), ^{ //
      // Perform your HTTP request (this runs on the main thread)
    } ) ;
    

    The MAIN_QUEUE runs on the main thread.

    So the first line of my HTTP get function looks like:

    void Server::get( string queryString, function onSuccess, 
                      function onFail )
    {
        if( ![NSThread isMainThread] )
        {
            warning( "You are issuing an HTTP request on NOT the main thread. "
                     "This is a problem because if your thread exits too early, "
                     "I will be terminated and my delegates won't run" ) ;
    
            // From NOT the main thread:
            dispatch_async( dispatch_get_main_queue(), ^{
              // Perform your HTTP request (this runs on the main thread)
              get( queryString, onSuccess, onFail ) ; // re-issue the same HTTP request, 
              // but on the main thread.
            } ) ;
    
            return ;
        }
        // proceed with HTTP request normally
    }
    

提交回复
热议问题