Detecting when you're in/out of the main thread in Monotouch


Is there a way in iOS / 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 MonoTouch equivalent is NSThread.Current.IsMainThread.


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.

This video can help you solving your question :)
By: admin