【发布时间】:2011-01-27 02:40:50
【问题描述】:
我刚刚在 NSOperation 中遇到了一个我修复但不理解的奇怪行为。
我按照文档对 NSOperation 进行了子类化。当我使用下面的 main 方法时,应用程序将使用 100% 或更多的 CPU 时间。
-(void)main
{
@try
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//Cycle forever until told to cancel
while (![self isCancelled])
{
}
[pool release];
}
@catch(...)
{
// Do not rethrow exceptions.
}
//Finish executing
[self completeOperation]; //Send notificatios using KVO
}
相反,当我使用下面的 main 方法时,应用程序使用了 3% 的 CPU 时间。
-(void)main
{
@try
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//Create the initial delayed timers
NSTimer *startUpTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:startUpTimer forMode:NSRunLoopCommonModes];
[runLoop run];
//Cycle forever until told to cancel
while (![self isCancelled])
{
}
[pool release];
}
@catch(...)
{
// Do not rethrow exceptions.
}
//Finish executing
[self completeOperation]; //Send notificatios using KVO
}
这种奇怪的行为似乎归因于计时器。如果要求定时器不重复自身,则应用程序使用 100% CPU 时间,但如果要求定时器重复自身,则 CPU 使用率正常。
似乎当线程上没有运行任何东西时,CPU 使用率确实很高(我认为情况正好相反)。关于为什么会这样的任何建议?
谢谢。
【问题讨论】:
标签: objective-c multithreading cocoa nsoperation