Can an open, but inactive, NSStream that is scheduled on the main thread be moved to a different thread?

独自空忆成欢 提交于 2019-12-25 02:19:51

问题


I am using (and am required to use) a third-party framework to which I do not have source. The third-party framework handles creating an authenticated client/server connection and hands back a pair of open NSStreams. The challenge that I have is the NSStreams are scheduled on the main thread (creating situations where the UI may become unresponsive - which I would like to avoid).

At the point that the streams are handed off from the third party framework, no network traffic is in progress. So, I am wondering if I could just unschedule and reschedule the NSStreams.

Does anyone know if it is possible to unschedule an open NSStream and reschedule it on a different run loop on a different thread? Will that cause problems? Are there any code examples out there?

Thanks in advance!

Aaron


回答1:


If I understand your application correctly, it means that your application receives references to a particular stream, and you are in charge of reading everything on the steams. Reading these streams should be something that you force into the background from your application via a NSThread, NSOperation or other threading mechanism.

Example:

In whatever file your tieing in this NSInputStream:

@property (strong, nonatomic) NSInvocationOperation *parseOp; 

(id)startInputRead:(NSInputStream *)input {
    if([input hasBytesAvailable]) {
        self.parseOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(readAndStoreInput:) object:inputStream];

    }

Where your reader is something like:

(void)readAndStoreInput:(NSInputSteam*) input{
     //process your input steam into your system in the background

}

This is a short example of just how you would do this for the input side. You could also queue up work for the output steam in a similar fashion. This should make everything run concurrently and your app stay responsive.



来源:https://stackoverflow.com/questions/10739966/can-an-open-but-inactive-nsstream-that-is-scheduled-on-the-main-thread-be-move

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!