views:

33

answers:

1

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.

ETA: For anyone coming along later: Obj-C answer from JP below. The MonoTouch equivalent is NSThread.Current.IsMainThread.

+2  A: 

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!");
JP
That does the trick -- thanks!
David Moles