[mono-android] Analog for Control.[Begin]Invoke

Jonathan Pryor jonp at xamarin.com
Tue Feb 21 20:31:25 UTC 2012


On Feb 20, 2012, at 11:50 AM, Chris Tacke wrote:
> I've moved to something a bit simpler that, from initial tests anyways, appears to work.  Does this seem reasonable though (I think it assumes that the UIInvoker class itself is created on the UI thread):
> 
>    public class UIInvoker : DisposableBase
>    {
>        private Activity m_activity = new Activity();
> 
>        public void Invoke(Delegate method)
>        {
>            m_activity.RunOnUiThread(delegate
>            {
>                method.DynamicInvoke(null);
>            });
>        }

I wouldn't suggest this solution, as this avoids a great deal of Activity initialization; you have a "half-baked" Activity instance. (For those reading along at home, Activity.attach() is never invoked; Activity.attach() is called in android.app.ActivityThread, which requires that you go through the Context.startActivity() infrastructure, which `new Activity()` obviously doesn't.)

That said, it works...because Activity.runOnUiThread() doesn't use Activity.mUiThread for anything except reference comparison, but I have no idea how long that will be the case.

What I would instead suggest is:

	public void Invoke(Delegate method)
	{
		using (var handler = new Android.OS.Handler(Android.OS.Looper.MainLooper))
			handler.Post(delegate {
					method.DynamicInvoker(null);
			});
	}

 - Jon



More information about the Monodroid mailing list