NSThread sleepfortimeinterval blocks main thread

前端 未结 3 1511
庸人自扰
庸人自扰 2020-12-31 05:44

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

 [NSThr         


        
相关标签:
3条回答
  • 2020-12-31 06:20

    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
        })
    }
    
    0 讨论(0)
  • 2020-12-31 06:34

    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];
    
    0 讨论(0)
  • 2020-12-31 06:45

    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
        }); 
    });
    
    0 讨论(0)
提交回复
热议问题