Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting when you're in/out of the main thread in Xamarin.iOS

Tags:

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.

like image 357
David Moles Avatar asked Oct 18 '10 19:10

David Moles


1 Answers

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!"); 
like image 161
Jay Peyer Avatar answered Oct 14 '22 15:10

Jay Peyer