简体   繁体   English

接收数据时,GCDAsyncSocket会冻结UI

[英]GCDAsyncSocket freezes UI when receiving data

I'm new to GCD principles and GCDAsyncSocket, but I'm using it in my project. 我是GCD原理和GCDAsyncSocket的新手,但是我在项目中使用了它。 I initialize the GCD socket in the AppDelegate with: 我使用以下命令在AppDelegate中初始化GCD套接字:

self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

Now, everything runs fine, sending and receiving works fine. 现在,一切正常,发送和接收工作正常。 But, if the socket receives a lot of data very fast (like a 1000 or so messages from a 'for loop' from the server), the app's UI freezes till it has received everything (Although there are no errors in the received messages). 但是,如果套接字非常快地接收大量数据(例如来自服务器“ for循环”的1000条左右消息),则应用程序的UI会冻结,直到接收到所有内容为止(尽管接收到的消息中没有错误) 。

So what do I need to change to not let the UI freeze? 那么,我需要更改什么以不让UI冻结? Is it because it is using "dispatch_get_main_queue()", do I need to use another queue? 是否因为使用了“ dispatch_get_main_queue()”,是否需要使用另一个队列? if so, how should I go about it? 如果是这样,我应该怎么做? Or do I use threading or something like that? 还是我使用线程之类的东西?

Try creating your own concurrent serial background queue (turns out your not allowed to use a concurrent one), for example 尝试创建自己的并发串行后台队列(结果是不允许使用并发串行队列),例如

dispatch_queue_t queue = dispatch_queue_create("com.yourid.queue", DISPATCH_QUEUE_SERIAL);
self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue: queue];

Alternatively you can pass 'NULL' and GCDAsyncSocket will create its own queue. 或者,您可以传递“ NULL”,GCDAsyncSocket将创建自己的队列。

This should call the delegate methods in a background queue and hopefully stop your UI from freezing. 这应该在后台队列中调用委托方法,并希望阻止UI冻结。 The important thing to note here is, you can't update UI Elements on a background queue, so you have to do something like this in your delegate methods: 这里要注意的重要事情是,您无法在后台队列上更新UI元素,因此您必须在委托方法中执行以下操作:

- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
    //Do some calculations (in background queue)

    dispatch_async(dispatch_get_main_queue(), ^{
        //Update UI elements (in main queue)
    });
} 

(I hope I remembered this correctly) (我希望我没记错)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM