我有一个连续打开的 TCP 连接,用于与外部设备通信。通信管道中发生了很多事情,导致 UI 有时变得无响应。
我想将通信放在一个单独的线程中。我了解 detachNewThread
以及它如何调用 @selector
。我的问题是我不确定如何将它与类似 NSStream
?
最佳答案
您可能更愿意使用 Grand Central Dispatch ('GCD'),而不是手动创建线程和管理线程安全问题。这允许您发布 block ——它们是代码包和一些状态——在远离主线程和操作系统认为最合适的任何地方执行。如果您创建一个串行调度队列,您甚至可以确定,如果您在旧 block 尚未完成时发布一个新 block ,系统将等待它完成。
例如
// 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也值得一读。
关于ios - 线程 NSStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066266/