将非主运行循环任务转换为 GCD

发布于 2024-10-09 09:41:52 字数 880 浏览 0 评论 0原文

我有一个定期运行的任务,它最初设计为使用 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];
}

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

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:@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];
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见 2024-10-16 09:41:52

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

不过,回到最初的情况,您实际上并不需要创建线程或使用调度来运行计时器。运行循环的要点是您不需要创建线程来执行诸如计时器之类的简单操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文