检测您何时进入/退出 Xamarin.iOS 中的主线程 [英] Detecting when you're in/out of the main thread in Xamarin.iOS
问题描述
Xamarin/MonoTouch 有没有办法检测主线程中是否正在调用代码?
Is there a way in Xamarin/MonoTouch to detect whether code is being called in the main thread?
我正在寻找类似于 Java EventQueue.isEventDispatchThread()
的东西——我在 Swing 编程中发现它很方便 assert
时间(或者有时断言
它不是)——确保模型持续更新并从 EDT 读取,并且长时间运行的调用不会阻塞 UI.
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.
我想在我的 MonoTouch 应用程序中做同样的事情,以确保从 UI 调用/不从 UI 调用或包装在 InvokeOnMainThread
中的各种代码.
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
.
更新:对于以后出现的任何人:Obj-C下面来自 JP 的回答.Xamarin/MonoTouch 等效项是 NSThread.Current.IsMainThread
.
Updated: For anyone coming along later: Obj-C answer from JP below . The Xamarin/MonoTouch equivalent is NSThread.Current.IsMainThread
.
推荐答案
我对 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], @"Method called using a thread other than main!");
这篇关于检测您何时进入/退出 Xamarin.iOS 中的主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!