3

我有一个定期运行的任务,它最初设计为在一个单独的运行循环上运行,而不是使用 NSThread 和 NSTimer 的主运行循环。

调整它以利用 GCD 的最佳方法是什么?

当前代码:

-(void)initiateSomeTask
{
    [NSThread detachNewThreadSelector:@selector(startTimerTask) 
            toTarget:self withObject:nil];
}

-(void)startTimerTask
{
    // We won't get back the main runloop since we're on a new thread 
    NSRunLoop *myRunLoop = [NSRunLoop currentRunLoop]; 

    NSPort *myPort = [NSMachPort port];
    [myRunLoop addPort:myPort forMode:NSDefaultRunLoopMode];

    NSTimer *myTimer = [NSTimer timerWithTimeInterval:10 /* seconds */ 
            target:self selector:@selector(doMyTaskMethod) 
            userInfo:nil repeats:YES];

    [myRunLoop addTimer:myTimer forMode:NSRunLoopCommonModes];
    [myRunLoop run];
}

detachNewThreadSelector除了替换之外我还能做些什么dispatch_async吗?

4

1 回答 1

2

您可以将 NSTimer 的使用替换为 dispatch_source_create 与 DISPATCH_SOURCE_TYPE_TIMER 的使用。那么你就不需要运行循环了。

但是,回到最初的情况,您实际上并不需要创建线程或使用 dispatch 来运行计时器。运行循环的一种意义在于,您不需要创建线程来执行诸如计时器之类的简单操作。

于 2010-12-26T22:22:24.673 回答