Detecting when you're in/out of the main threa

2019-03-22 20:01发布

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.

3条回答
SAY GOODBYE
2楼-- · 2019-03-22 20:18

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());
}
查看更多
Evening l夕情丶
3楼-- · 2019-03-22 20:22

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.

查看更多
时光不老,我们不散
4楼-- · 2019-03-22 20:35

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!");
查看更多
登录 后发表回答