Forum Xamarin.iOS

InvokeOnMainThread vs BeginInvokeOnMainThread

victoriavictoria SEMember ✭✭✭

We all know and love the InvokeOnMainThread(Action) method, but I have seen a few projects where instead this pattern is used:

static NSObject Invoker = new NSObject();

public static void InvokedOnMainThread(Action Action)
    if (NSThread.Current.IsMainThread)
        Invoker.BeginInvokeOnMainThread(() => Action());        

Obviously this will let you access the main thread from classes that do not themselves inherit from NSObject, but is there some other reason why we should write like this?


  • InvokeOnMainThread will suspend the execution of your thread, and wait for the delegate to be executed on the main thread. When that completes, the thread resumes execution.
    BeginInvokeOnMainThread does not.

  • victoriavictoria SEMember ✭✭✭

    Aha! I guess in most cases it doesn't really make much difference what we use then. Thanks for clearing that up!

  • DanieleDaviDanieleDavi USMember

    Keep in mind that while debugging Xamarin.iOS applications, an error will be thrown if your code attempts to access a UI control from the wrong thread. The "IF" helps you to track down and fix these problems with the InvokeOnMainThread method. This only occurs while debugging and does not throw an error in release builds.

    Making the check will avoid to rise the error in debug.

Sign In or Register to comment.