NSThread sleepfortimeinterval阻止主线程 [英] NSThread sleepfortimeinterval blocks main thread

查看:1663
本文介绍了NSThread sleepfortimeinterval阻止主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to simulate a communication with a server. As the remote server will have some delays I want to use a background thread that has on it

 [NSThread sleepForTimeInterval:timeoutTillAnswer];

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

The thread is created with NSThread sub classing and started ... However I noticed that sleepForTimeInterval is blocking the main thread... Why??? Isn't a NSThread a backgroundThread by default?

这是线程的创建方式:

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

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

Further info: This is the bot thread subclas

- (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对象内部进行干预....

I want to call "messageForBot" from the main thread... also the background thread should call a method on the main thread to communicate.. The sleep for time intervail in inside the gManager object ....

推荐答案

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

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

这篇关于NSThread sleepfortimeinterval阻止主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆