正确释放 NSOperationQueue
我想知道解除分配 ivar NSOperationQueue 的正确方法是什么,以防它仍有一些操作正在运行,这通常在用户突然退出应用程序时发生。在一些示例中,我看到使用了 waitUntilAllOperationsAreFinished,如下所示:
- (void)dealloc {
[_queue cancelAllOperations];
[_queue waitUntilAllOperationsAreFinished];
[_queue release];
...
然而许多人建议避免这样做,因为它会挂起运行循环。那么释放_queue
的正确方法是什么?如果我不等待操作完成而继续发布,会发生什么情况?
I'd like to know what is the proper way to dealloc an ivar NSOperationQueue in case it has still some operations running, which can typically occur when the user suddenly quits the app. In some examples I saw the waitUntilAllOperationsAreFinished was used, like this:
- (void)dealloc {
[_queue cancelAllOperations];
[_queue waitUntilAllOperationsAreFinished];
[_queue release];
...
however many suggest to avoid doing so since it would hang the run loop. So what is the proper way to release the _queue
? And what happens if I don't wait for operations to be finished and just go on with the release?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在几乎所有情况下,调用
cancelAllOperations
就足够了。您唯一需要调用waitUntilAllOperationsAreFinished
的情况是您确实需要确保这些操作在继续之前已完成。例如,如果操作正在访问某些共享内存,您可能会这样做,并且如果您不等待,那么最终将有两个线程同时写入该共享内存。但是,我想不出任何合理的设计可以通过在
dealloc
方法中引起阻塞延迟来保护共享内存。有更好的同步机制可用。因此,简短的答案是:您不需要等待所有操作完成,除非您的应用程序出于某种原因特别需要它。
In almost all cases, calling
cancelAllOperations
will be sufficient. The only time you need to callwaitUntilAllOperationsAreFinished
is if you actually need to ensure that those operations are done before you move on.For example, you might do so if the operations are accessing some shared memory, and if you don't wait then you'll end up with two threads writing to that shared memory at the same time. However, I can't think of any reasonable design that would protect shared memory by causing a blocking delay in a
dealloc
method. There are far better sychronization mechanisms available.So the short answer is this: you don't need to wait for all operations to finish unless there's some reason your application specifically needs it.