title: iOS network on background thread causes application to hang
body: <p>I have an application that creates a background thread for the network messages. The application works nearly perfectly unless the server it connects to closes the connection. I am unsure of why this happens but any advice is greatly appreciated. I've included the snippets of code that can be followed to the problem. If something is vague or more detail is needed please let me know.</p>
  
  <pre><code>- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
  switch(eventCode) {
      case NSStreamEventErrorOccurred:
          {
              NSLog(@"NSStreamEventErrorOccurred");
  
              [self Disconnect:self];
          }
      }
  }
  
  - (void)Disconnect:(id)sender {
      [self performSelector:@selector(closeThread) onThread:[[self class]networkThread] withObject:nil waitUntilDone:YES];
  
      [outputStream close];
      [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
      [outputStream release];
      outputStream = nil;
  }
  
  + (NSThread*)networkThread
  {
      // networkThread needs to be static otherwise I get an error about a missing block type specifier
      static NSThread* networkThread = nil;
      static dispatch_once_t onceToken;
      dispatch_once(&amp;onceToken, ^{
          networkThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkThreadMain:) object:nil];
  
          [networkThread start];
      });
  
      return networkThread;
  }
  </code></pre>
  
  <p>The hang up occurs on the return networkThread line. After executing that line the application seems to hang and freeze and I can't put my finger on why.</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Here is the snippet of code for CloseThread for those interested</p>
  
  <pre><code>- (void)closeThread
  {   
      /*if(!inputStream)
          return;
  
      [inputStream close];
      [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
      [inputStream release];
      inputStream = nil;*/
  }
  </code></pre>