ios - 强制停止 NSOperation 或 GCD?

标签 ios nsoperation

在我的应用程序中,我在后台运行服务器。我正在使用 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/

相关文章:

ios - 取消操作时不调用 NSOperation dealloc

ios - NSOperationQueue 似乎会降低性能

iphone - 如何在 NSOperation 中启动异步 NSURLConnection?

ios - Advanced NSOperation - 在运行时添加依赖

iphone - Box2d - 赋予物体吸引力/重力

ios - 翻转图像以显示背面的 iOS

c++ - 架构 i386 "CScanner::CScanner(void*)"的 undefined symbol ,引用自

ios - iOS App 开发的 Swift 用户输入方法

objective-c - 为什么 NSOperations 和 sleep 不能正常工作?

ios - 如何阻止 GCD 调度 _after block 返回结果。可能很愚蠢