开发者

Why is NSTimer blocked while another thread is running?

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(length开发者_如何学PythonyMethod) 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.


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.


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 !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜