문제

sleep works well but runUntilDate doesn't work on a background thread. But why?

-(IBAction) onDecsriptionThreadB:(id)sender
{
 dispatch_async(dispatch_get_global_queue(0, 0), ^{

    while (1)
    {
        NSLog(@"we are here");
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
        //sleep(2);
    }        
  });    
}
도움이 되었습니까?

해결책

If no input sources or timers are attached to the run loop, this method exits immediately;

If you want to use runUntilDate you must add timer or input sources. My correct version is:

while (1)
{
    NSLog(@"we are here");
    [NSTimer scheduledTimerWithTimeInterval:100 target:self selector:@selector(doFireTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
    //sleep(2);
}  

다른 팁

Take a look at the question Difference in usage of function sleep() and [[NSRunLoop currentRunLoop] runUntilDate]

NSRunLoop is better because it allows the runloop to respond to events while you wait. If you just sleep your thread your app will block even if events arrive (like the network responses you are waiting for).

Also the documentation of NSRunLoop says that:

If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate: until the specified expiration date.

If you are using GCD, the purpose is to generally get away from doing complicated thread coding right. What is the bigger purpose of you trying to do this. May be your big picture context will help explain the problem better.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top