编写 NSOperation 友好的方法

发布于 2024-10-07 09:33:42 字数 736 浏览 3 评论 0原文

我有一个对象(Processor),其中包含多个执行冗长计算的方法。我想在主线程和 NSOperation 子类中使用这些方法。

在我的 NSOperation 子类代码中,我重复调用 isCancelled,因此取消响应相当灵敏。但是,当操作调用这些冗长的 Processor 方法之一时,在该方法返回之前它无法响应取消。

有没有一种好的方法来编写方法,以便它们可以在有操作和没有操作的情况下使用?我正在考虑向我的 CPU 密集型 Processor 方法添加一个 operation 参数,并像这样编写它们:

- (void)calculateWithOperation:(NSOperation *)operation {
    do {
        if (operation != nil && [operation isCancelled]) {
            return;
        }
        // Do some more calculation...
    } while (! finished);
}

// For convenient main thread execution.
- (void)calculate {
    [self calculateWithOperation:nil];
}

之前有其他人遇到过这个问题吗?有更好的办法吗?

I have an object (Processor) containing several methods that perform lengthy calculations. I'd like to use those methods both on the main thread and in NSOperation subclasses.

Inside my NSOperation subclass code I repeatedly call isCancelled, so cancellation is fairly responsive. However, when the operation calls one of those lengthy Processor methods, it isn't able to respond to cancellation until that method returns.

Is there a good way to write methods so they can be used both with and without operations? I'm considering adding an operation argument to my CPU-intensive Processor methods and writing them like this:

- (void)calculateWithOperation:(NSOperation *)operation {
    do {
        if (operation != nil && [operation isCancelled]) {
            return;
        }
        // Do some more calculation...
    } while (! finished);
}

// For convenient main thread execution.
- (void)calculate {
    [self calculateWithOperation:nil];
}

Has anyone else run into this issue before? Is there a better way?

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

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

发布评论

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

评论(1

红颜悴 2024-10-14 09:33:42

NSOperation 响应取消的唯一方法是尽可能频繁地检查 isCancelled 是否已取消。毕竟,它只是一个在设置标志时需要退出的线程。基本上,需要 isCancelled 基础设施来正常释放操作的资源。所以我想说你只需要在昂贵的方法中添加检查即可。

The only way for an NSOperation to respond to canceling is to check if it's isCancelled as frequently as feasible. After all, it's just a thread which needs to exit when a flag is set. Basically, the isCancelled infrastructure is needed to gracefully free the operation's resources. So I'd say you just have to pepper the expensive method with checks.

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