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
.
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:
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.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: