我有一个持续打开的TCP连接,用于与外部设备通信。在通信管道中发生了很多事情,导致UI有时变得没有响应。
我想把通信放在一个单独的线程上。我理解detachNewThread以及它是如何调用@selector的。我的问题是,我不确定如何将其与NSStream之类的东西结合使用
发布于 2012-01-30 23:41:55
与手动创建线程和管理线程安全问题相比,您可能更喜欢使用中央调度中心(GCD)。这允许你在操作系统认为最合适的地方,在远离主线程的地方执行代码包和一些状态关闭的块。如果你创建了一个串行调度队列,你甚至可以确定,如果你发布了一个新的数据块,而旧的数据块还没有完成,系统会一直等到它完成。
例如。
// you'd want to make this an instance variable in a real program
dispatch_queue_t serialDispatchQueue =
dispatch_queue_create(
"A handy label for debugging",
DISPATCH_QUEUE_SERIAL);
...
dispatch_async(serialDispatchQueue,
^{
NSLog(@"all code in here occurs on the dispatch queue ...");
});
/* lots of other things here */
dispatch_async(serialDispatchQueue,
^{
NSLog(@"... and this won't happen until after everything already dispatched");
});
...
// cleanup, for when you're done
dispatch_release(serialDispatchQueue);快速介绍一下GCD is here,苹果的more thorough introduction也值得一读。
https://stackoverflow.com/questions/9066266
复制相似问题