1

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);
    }        
  });    
}
madth3
  • 7,275
  • 12
  • 50
  • 74
Voloda2
  • 12,359
  • 18
  • 80
  • 130
  • I have never used `runUntilDate` and maybe I'm wrong, but reading the name for me this method should do the opposite of `sleep()` – tkanzakic Jan 10 '13 at 12:38
  • Yes, actually it runs and don't sleep, but it don't returned until timeout. – Voloda2 Jan 12 '13 at 12:37

2 Answers2

3

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);
}  
Voloda2
  • 12,359
  • 18
  • 80
  • 130
  • very nice - in fact that works. But why does it work if there is a timer associated to the run loop? Will this remain like this in new updates? Doe you have by any chance a reference? Many thanks – user387184 Apr 12 '13 at 07:54
  • ...I mean especially since you have not even defined a method doFireTimer:, at least in my case it does not even crash without this method – user387184 Apr 12 '13 at 08:15
  • Actually, it will crash after 100 seconds when the timer fires and the missing doFireTimer method is called. – don Jun 21 '13 at 15:11
1

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.

Community
  • 1
  • 1
Srikanth
  • 1,725
  • 2
  • 10
  • 11