可以在Objective-C中的另一个线程中捕获从一个线程抛出的异常吗? [英] Can I catch exceptions thrown from one thread in another thread in Objective-C?

查看:115
本文介绍了可以在Objective-C中的另一个线程中捕获从一个线程抛出的异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以捕获另一个线程中的一个线程抛出的异常?例如,我从我的主线程中产生一个线程。产生的线程可能会引发未捕获的异常。有可能让产卵线程捕获这些异常吗?

Is it possible to catch an exception thrown from one thread in another thread? For example, I am spawning a thread from my main thread. The spawned thread may throw uncaught exceptions. Is it possible to have the spawning thread catch these exceptions?

一个解决方案是从生成的线程的入口点捕获异常,并通过处理异常发布 NSNotification 。然后,产卵线程可以收听这些 NSNotification s。但是,这个解决方案似乎有点软硬,因为它基本上是重新实现了@catch子句,给出了不同类型的 NSException 作为参数。我想检查是否有其他解决方案可用。

One solution would be to catch the exceptions from the entry point of the spawned thread and "handle" the exception by posting an NSNotification. Then, the spawning thread can listen for these NSNotifications. However, this solution seems a little corky because it's basically reimplementing the @catch clause given different types of NSExceptions as a parameter. I wanted to check if any other solutions are available.

推荐答案

这是不可能和毫无意义的。抛出的线程无法知道生成的线程当前是否正在 try 块中运行。如果没有,它会做什么?延期投掷,直到spawner关心抓住?如果没有,怎么办?

It's impossible and pointless. The throwing thread has no way of knowing if the spawning thread is currently running within a try block. If not, what would it do? Defer throwing until the spawner cares to catch? What if it never does?

考虑另一种情况。而在spawner线程正在做某些事情并且恰好处于不一致状态时,工作线程中抛出异常 - 例如,它正在更新某些数据结构的中间。异常会中断执行流程,并使数据处于不一致的状态。更不要说Spawner正在做的任何其他好的任务将永远是不完整的。

Consider another scenario. And exception is thrown in the worker thread while the spawner thread is doing something and happens to be in inconsistent state - say, it's in the middle of updating some data structure. The exception would break the flow of execution and leave the data in said inconsistent state. Not to mention that whatever otherwise good task that the spawner was doing would remain forever incomplete.

所以正确的方法是抓住工作的顶层使用类似 [NSObject performSelector:] 的线程传递给spawner线程。应该通知Spawner关于boolboos在一个或多个生物中的一般想法是坚实的,但是投掷者的例外是spavner是不正确的。注意 - 我说扔,而不是通过Cocoa提供的其他机制。

So the right way to go about it is catching in the top level of the worker thread and passing to the spawner thread using something like [NSObject performSelector:]. The general idea that the spawner should be notified about the booboos in the spawnee(s) is solid, but throwing spawnee's exceptions to the spawner is not right. Note - I said "throwing", as opposed to passing by other mechanisms that Cocoa offers.

这篇关于可以在Objective-C中的另一个线程中捕获从一个线程抛出的异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆