NSThread sleepfortimeinterval blocks main thread

谁说胖子不能爱 提交于 2019-11-30 11:29:34
John

It blocks whatever thread sleepForTimeInterval is running on. Run it on another thread to simulate your server delay like this:

dispatch_queue_t serverDelaySimulationThread = dispatch_queue_create("com.xxx.serverDelay", nil);
dispatch_async(serverDelaySimulationThread, ^{
     [NSThread sleepForTimeInterval:10.0];
     dispatch_async(dispatch_get_main_queue(), ^{
            //Your server communication code here
    }); 
});

Try create a method in your thread class called sleepThread

-(void)sleepThread
{
   [NSThread sleepForTimeInterval:timeoutTillAnswer];
}

Then to make it sleep from your main thread

[self.botThread performSelector:@selector(sleepThread) onThread:self.botThread withObject:nil waitUntilDone:NO];

To send updated to your main thread from your bot thread.

dispatch_async(dispatch_get_main_queue(), ^{
    [MainClass somethinghasUpdated];
});

Side Note

To create the RunLoop I think all you need to do is

// Run the Current RunLoop
[[NSRunLoop currentRunLoop] run];

Swift:

let nonBlockingQueue: dispatch_queue_t = dispatch_queue_create("nonBlockingQueue", DISPATCH_QUEUE_CONCURRENT)
dispatch_async(nonBlockingQueue) {
    NSThread.sleepForTimeInterval(1.0)
    dispatch_async(dispatch_get_main_queue(), {
        // do your stuff here
    })
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!