检测您何时进入/退出 Xamarin.iOS 中的主线程
Xamarin/MonoTouch 有没有办法检测主线程中是否正在调用代码?
我正在寻找类似于 Java 的 EventQueue.isEventDispatchThread()
的东西 - 我发现在 Swing 编程中,时不时地断言
(或者有时会断言
事实并非如此)——确保模型持续更新并从 EDT 读取,并且长时间运行的调用不会阻塞 UI。
我想在我的 MonoTouch 应用程序中执行相同的操作,以确保不会从 UI 调用各种代码,或将其包装在 InvokeOnMainThread
中。
更新:对于后来的任何人:Obj-C 下面来自 JP 的回答。 Xamarin/MonoTouch 等效项是 NSThread.Current.IsMainThread
。
Is there a way in Xamarin/MonoTouch to detect whether code is being called in the main thread?
I'm looking for something like the equivalent of Java's EventQueue.isEventDispatchThread()
-- I've found in Swing programming it's handy to assert
that from time to time (or sometimes to assert
that it's not) -- making sure that models are consistently updated and read from the EDT, and that long-running calls don't block the UI.
I'd like to do the same in my MonoTouch app, to ensure that various bits of code are/aren't called from the UI, or wrapped in InvokeOnMainThread
.
Updated: For anyone coming along later: Obj-C answer from JP below . The Xamarin/MonoTouch equivalent is NSThread.Current.IsMainThread
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我对 Monotouch 了解不多,但在 iOS 中
+[NSThread isMainThread]
可能就是您正在寻找的。有时在编写多线程代码时,我会放入这样的断言:
I don't know much about Monotouch, but in iOS
+[NSThread isMainThread]
might be what you're looking for.Occasionally when writing multithreaded code, I will put in an assert like this:
NSAssert([NSThread isMainThread], errorDesc) 的唯一问题是您在进行此调用时最好在主线程中。如果您碰巧在辅助线程中进行调用,那么您的应用程序就会崩溃!所以这有点毫无意义。
最好只使用
[NSThread isMainThread]
然后评估它返回的 BOOL 值。The only problem with
NSAssert([NSThread isMainThread], errorDesc)
is that you BETTER be in the main thread when making this call. If you happen to be in a secondary thread and make the call then your application crashes! So it's kind of pointless.It's better just to simply use
[NSThread isMainThread]
then assess the BOOL value it returns.您可以在 Monotouch / Xamarin.ios 中这样做。
此检查对于避免尝试从后台线程修改 UI 时可能发生的错误非常有用。可以这样做:
You can do like this in Monotouch / Xamarin.ios
This check is very useful to avoid the error that might occur when trying to modify the UI from a background Thread. Something Like this can be done: