为什么在另一个线程正在运行时NSTimer被阻止

为什么在另一个线程正在运行时NSTimer被阻止

本文介绍了为什么在另一个线程正在运行时NSTimer被阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在iPhone的后台运行冗长的任务.我从performSelectorInBackground开始.我还在主线程上创建了一个NSTimer,目的只是为了检查一切是否正常.我希望计时器会在其他线程执行此操作的同时运行:

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!");
}

lenghtyMethod执行许多操作,包括使用 ASIHTTPRequest 等进行URL下载.

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

NSLog的输出如下:

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 ...

问题在于后台线程似乎阻塞了计时器.我的理解是,performSelectorInBackground应该在与主循环分开的新线程中运行.

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.

为便于记录,线程主要在执行I/O(加载URL),因此OS应该有足够的时间来切换线程.在模拟器和实际设备上都会发生这种情况.

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.

推荐答案

根据 ASIHTTPRequest :

否则,如果您使用默认回调,它们将在主线程上运行.

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

这篇关于为什么在另一个线程正在运行时NSTimer被阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:34