正确释放 NSOperationQueue

发布于 2024-10-11 20:25:29 字数 401 浏览 7 评论 0原文

我想知道解除分配 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 技术交流群。

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

发布评论

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

评论(1

隔岸观火 2024-10-18 20:25:29

在几乎所有情况下,调用 cancelAllOperations 就足够了。您唯一需要调用 waitUntilAllOperationsAreFinished 的情况是您确实需要确保这些操作在继续之前已完成。

例如,如果操作正在访问某些共享内存,您可能会这样做,并且如果您不等待,那么最终将有两个线程同时写入该共享内存。但是,我想不出任何合理的设计可以通过在 dealloc 方法中引起阻塞延迟来保护共享内存。有更好的同步机制可用。

因此,简短的答案是:您不需要等待所有操作完成,除非您的应用程序出于某种原因特别需要它。

In almost all cases, calling cancelAllOperations will be sufficient. The only time you need to call waitUntilAllOperationsAreFinished 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.

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