ios - 线程 NSStream

标签 ios networking

我有一个连续打开的 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/

相关文章:

android - 在桌面上查看移动网站

ios - 将UIImage着色为其他颜色,或者从矢量生成UIImage

ios - UIView 的不透明度和 alpha 是否相同

c# - 如何获取所有连接到网络的计算机列表?

java - 连接短时间中断后 TCP 连接被拒绝

c++ - 在Linux中,当同一套接字上的accept()调用正在进行时,套接字描述符在某些条件下从另一个线程关闭?

ios - 快速错误线程 1 : EXC_BAD_INSTRUCITON

ios - 应用上传到App Store后状态为inactive

android - webview 错误屏幕显示空白页

c# - 测试互联网连接的最快方法