NSThread sleepfortimeinterval阻止主线程

时间:2013-08-15 09:21:06

标签: ios nsthread

我想模拟与服务器的通信。由于远程服务器会有一些延迟,我想使用其上的后台线程

 [NSThread sleepForTimeInterval:timeoutTillAnswer];

使用NSThread子类创建线程并启动...但是我注意到sleepForTimeInterval正在阻塞主线程...为什么???默认情况下,NSThread不是backgroundThread吗?

这就是线程的创建方式:

   self.botThread = [[PSBotThread alloc] init];
    [self.botThread start];

更多信息: 这是机器人线程子类

- (void)main
{
    @autoreleasepool {
        self.gManager = [[PSGameManager alloc] init];
        self.comManager = [[PSComManager alloc] init];
        self.bot = [[PSBotPlayer alloc] initWithName:@"Botus" andXP:[NSNumber numberWithInteger:1500]];
        self.gManager.localPlayer = self.bot;
        self.gManager.comDelegate = self.comManager;
        self.gManager.tillTheEndGame = NO;
        self.gManager.localDelegate = self.bot;
        self.comManager.gameManDelegate = self.gManager;
        self.comManager.isBackgroundThread = YES;
        self.comManager.logginEnabled = NO;
        self.gManager.logginEnabled = NO;
        self.bot.gameDelegate = self.gManager;
        BOOL isAlive = YES;
        // set up a run loop
        NSRunLoop *runloop = [NSRunLoop currentRunLoop];
        [runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [self.gManager beginGameSP];
        while (isAlive) { // 'isAlive' is a variable that is used to control the thread existence...
            [runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }



    }
}

- (void)messageForBot:(NSData *)msg
{
    [self.comManager didReceiveMessage:msg];
}

我想从主线程中调用“messageForBot”...后台线程也应该在主线程上调用一个方法进行通信..睡眠时间在gManager对象内部进行干预....

3 个答案:

答案 0 :(得分:22)

它阻止运行sleepForTimeInterval的任何线程。在另一个线程上运行它来模拟服务器延迟,如下所示:

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
    }); 
});

答案 1 :(得分:1)

尝试在名为sleepThread

的线程类中创建一个方法
-(void)sleepThread
{
   [NSThread sleepForTimeInterval:timeoutTillAnswer];
}

然后让它从主线程中休眠

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

从机器人线程发送更新到主线程。

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

旁注

要创建RunLoop,我认为您需要做的就是

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

答案 2 :(得分:0)

夫特:

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
    })
}