0

我有一个为网络消息创建后台线程的应用程序。除非它连接到的服务器关闭连接,否则该应用程序几乎可以完美运行。我不确定为什么会发生这种情况,但非常感谢任何建议。我已经包含了可以解决问题的代码片段。如果某些内容含糊不清或需要更多细节,请告诉我。

- (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;
}

挂断发生在返回 networkThread 线上。执行该行后,应用程序似乎挂起并冻结,我无法确定原因。

提前致谢。

编辑

这是 CloseThread 的代码片段,供感兴趣的人使用

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

    [inputStream close];
    [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [inputStream release];
    inputStream = nil;*/
}
4

1 回答 1

1

我建议改变:

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

至:

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

也就是说,不要等待。

于 2012-09-19T23:46:44.270 回答