質問

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.

- (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(&onceToken, ^{
        networkThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkThreadMain:) object:nil];

        [networkThread start];
    });

    return networkThread;
}

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.

Thanks in advance.

EDIT

Here is the snippet of code for CloseThread for those interested

- (void)closeThread
{   
    /*if(!inputStream)
        return;

    [inputStream close];
    [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [inputStream release];
    inputStream = nil;*/
}
役に立ちましたか?

解決

I suggest changing:

[self performSelector:@selector(closeThread) onThread:[[self class]networkThread] withObject:nil waitUntilDone:YES];

to:

[self performSelector:@selector(closeThread) onThread:[[self class]networkThread] withObject:nil waitUntilDone:NO];

That is, don't wait.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top