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

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


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!");


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.


You can do like this in Monotouch / Xamarin.ios

        if (NSThread.Current.IsMainThread)        {            //You are in the MainThread        } 

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:

if (NSThread.Current.IsMainThread){    DoSomething();}else{    BeginInvokeOnMainThread(() => DoSomething());}