Why is NSTimer blocked while another thread is running?

≡放荡痞女 提交于 2019-12-07 16:48:18

问题


I'm trying to run a lenghty task in the background on the iPhone. I start it with performSelectorInBackground. I also create a NSTimer on the main thread just to check if things are working. I expected that the timer would run while the other thread does it's thing:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
                   selector:@selector(onTimerEvent:)
                   userInfo:nil repeats:YES];   

   [self performSelectorInBackground:@selector(lengthyMethod) withObject:nil];

    NSLog(@"Here we go!");
}

- (void)onTimerEvent:(NSTimer *)timer
{
    NSLog(@"timer!");
}

The lenghtyMethod performs lots of stuff, including URL downloads using ASIHTTPRequest etc.

The output from NSLog looks like this:

2011-03-11 15:17:07.470 MyApp[6613:207] Here we go!    
2011-03-11 15:17:07.570 MyApp[6613:207] timer!
2011-03-11 15:17:07.670 MyApp[6613:207] timer!

// ... several seconds of output from lenghtyMethod omitted ...

2011-03-11 15:17:11.075 MyApp[6613:207] timer!
2011-03-11 15:17:11.170 MyApp[6613:207] timer!
// ... etc ... timer runs as expected when the call is completed ...

The problem is that the background thread seems to block the timer. My understanding of this was that performSelectorInBackground should run in a new thread separate from the main loop.

I don't get this. While the thread is running I get no output from the timer. Once the call is complete, the timer starts logging again.

For the record, the thread is mostly doing I/O (loading URLs) so there should be ample time for the OS to switch threads. This happens both in the simulator and on the actual device.


回答1:


According to ASIHTTPRequest:

For more complex situations, or where you want to parse the response in the background, create a minimal subclass of ASIHTTPRequest for each type of request, and override requestFinished: and failWithProblem:.

Otherwise if you use the default callbacks, they will be run on the main thread.




回答2:


NSTimer run on the same thread.
It call the event method on the main thread.

Your lengthyMethod method probably use the main tread to do some operations.
There was 2 ticks before this main thread block.
Check it !



来源:https://stackoverflow.com/questions/5274236/why-is-nstimer-blocked-while-another-thread-is-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!