If you want to do this from your PCL / shared code and everywhere else in your project. You have two options doing this.
Cross platform way, using the native mechanisms
add this to PCL
public class InvokeHelper
{
public static Action<Action> Invoker;
public static void Invoke(Action action)
{
Invoker?.Invoke(action);
}
}
add this to iOS (e.g. AppDelegate)
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// ...
InvokeHelper.Invoker = InvokeOnMainThread;
return true;
}
add this to Android (e.g. your application class)
[Application]
class MainApplication : Application
{
protected MainApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void OnCreate()
{
base.OnCreate();
InvokeHelper.Invoker = (action) =>
{
var uiHandler = new Handler(Looper.MainLooper);
uiHandler.Post(action);
};
}
}
And then you can call from your shared code
InvokeHelper.Invoke(() => DoSomething("bla"));
Complete cross platform way
You can implement InvokeHelper cross platform, too.
public class InvokeHelper
{
// assuming the static initializer is executed on the UI Thread.
public static SynchronizationContext mainSyncronisationContext = SynchronizationContext.Current;
public static void Invoke(Action action)
{
mainSyncronisationContext?.Post(_ => action(), null);
}
}