gpt4 book ai didi

ios - 强制停止 NSOperation 或 GCD?

转载 作者:行者123 更新时间:2023-11-28 22:35:04 25 4
gpt4 key购买 nike

在我的应用程序中,我在后台运行服务器。我正在使用 NSOperation这样做。 (我以前用过 GCD 但我需要能够停止它,所以我切换到 NSOperation ,但我仍然不知道如何。)

基本上,我的 NSOperation子类看起来像这样:

- (void)main {
server_main(var1, var2);
}

由于这是一个服务器,server_main函数基本不返回。我也无法控制该功能的实现。

有时,用户会更改服务器的设置。发生这种情况时,我想停止然后重新启动服务器。如果我理解正确,我需要做类似 if (self.isCancelled) 的事情在NSOperation子类,但因为它将卡在 server_main 中功能,我怀疑它是否真的有效。

那么我怎样才能停止服务器呢?

非常感谢!

最佳答案

要正确执行此操作,请参阅 Responding to Cancellation EventsConcurrency Programming Guide 中,它说:

Although the NSOperation class provides a way for clients to cancel an operation, recognizing the cancellation event is voluntary by necessity. If an operation were terminated outright, there might not be a way to reclaim resources that had been allocated. As a result, operation objects are expected to check for cancellation events and to exit gracefully when they occur in the middle of the operation.

To support cancellation in an operation object, all you have to do is call the object’s isCancelled method periodically from your custom code and return immediately if it ever returns YES.

这是一种冗长的说法,我真的认为您需要能够更改 server_main 以便它:

  • 定期检查isCancelled,或者

  • 让它提供一个回调/进度委托(delegate)方法 block ,这样您就可以自己执行此操作,还可以调用一些额外的函数/方法来取消 server_main,让它进行关键清理-向上过程。

如果您只是开始终止进程​​(如果可以的话),您无疑会泄漏资源或使 server_main 处于不一致状态。

我知道这不是您要找的答案,但这是取消操作的方式。对不起。

关于ios - 强制停止 NSOperation 或 GCD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16317833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com