Async Android callback methods (OnCreate, OnResume, OnBind, GetView etc.) support in Xamarin.Android

LukasNLukasN CZMember ✭✭

Hi,
is there a way to make Android callback methods async to fully utilize async/await keywords in my code? Is it supported in Xamarin.Android? If not when will be?

Best Answer

Answers

  • LukasNLukasN CZMember ✭✭

    Yeah, it works for methods with void return type but e.g. GetView has return type View. Async methods require return type void or Task<...> in this case Task. So I'm unable to override it.

  • TallMcPaulTallMcPaul USMember

    I've been re-factoring a Xamarin.Android app to use Async and I've noticed something peculiar about async callback methods. If an Activity's OnCreate method is made async, OnResume starts before OnCreate has finished.

    [Activity(Label = "DemoAsync", MainLauncher = true)]
    public class DemoAsync : Activity
    {
        protected override async void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
    
            Console.WriteLine("OnCreate - Starting Task");
            await DoSomething();
            Console.WriteLine("OnCreate - Finished Task");
        }
    
        protected override void OnResume()
        {
            base.OnResume();
    
            Console.WriteLine("OnResume");
        }
    
        private async Task DoSomething()
        {
            await Task.Delay(3000);
        }
    }
    

    Produces the output:

    • OnCreate - Starting Task
    • OnResume
    • OnCreate - Finished Task

    I'm not sure whether this is expected behaviour or not, but I can understand why it would happen

  • CheesebaronCheesebaron DKInsider, University mod

    That would be the expected behavior because you return to the method when the awaited method is done.

    Also in your DoSomething method you could just return the Task instead of awaiting it, that is a minor thing.

  • TallMcPaulTallMcPaul USMember
    edited February 2015

    Thanks Cheesebaron,

    It's quite common to make event handlers async void but in this case it's possible that OnResume runs before the Activity is fully initialised in async OnCreate which is what tripped me up. Since we have no control over whether OnCreate is awaited, the only proper solution is to move long running tasks out with initialisation which is probably a good idea anyway.

Sign In or Register to comment.