我有一个为网络消息创建后台线程的应用程序。除非连接的服务器关闭连接,否则应用程序几乎完美地工作。我不确定为什么会发生这种情况,但我们非常感谢任何建议。我已经包含了可以遵循问题的代码片段。如果某些内容含糊不清或需要更多详细信息,请告知我们。
- (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;*/
}
答案 0 :(得分: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];
也就是说,不要等。