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?
If I understand your question correctly, it already is:
protected async override void OnCreate(Bundle bundle)
//Other code etc.
var myData = await MyService.GetDataAsync();
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.
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)
Console.WriteLine("OnCreate - Starting Task");
Console.WriteLine("OnCreate - Finished Task");
protected override void OnResume()
private async Task DoSomething()
Produces the output:
I'm not sure whether this is expected behaviour or not, but I can understand why it would happen
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.
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.
Xamarin Inc., as a wholly-owned Microsoft subsidiary acting as a separate legal entity, adheres to the Microsoft Privacy Statement: Privacy & cookies