开发者

Converting non-main runloop tasks to GCD

开发者 https://www.devze.com 2023-02-01 01:18 出处:网络
I have a task that runs periodically and it was originally designed to run on a separate run loop than the main runloop using NSThread and NSTimer.

I have a task that runs periodically and it was originally designed to run on a separate run loop than the main runloop using NSThread and NSTimer.

What's the best way to adapt this to take advantage of GCD?

Current code:

-(void)initiateSomeTask
{
    [NSThread detachNewThreadSelector:@s开发者_如何学Pythonelector(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];
}

Is there anything I can do besides replace detachNewThreadSelector with dispatch_async?


You can replace the use of NSTimer with use of dispatch_source_create with DISPATCH_SOURCE_TYPE_TIMER. You won't need a run loop then.

Back in the original case, though, you don't really need to make a thread or use dispatch to run a timer. Kind of the point of run loops is that you don't need to make a thread to do something simple like a timer.

0

精彩评论

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