Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# / MonoTouch: how to call an async method when a ViewController is created/appears

Xamarin released support for async/await which really simplifies the development of responsive UI in mobile platforms. I'd like to take advantage of it and increase the programming level of my code by using async/await stuff from now on.

However, since I'm relatively new to C# and haven't used async/await before I'm having trouble to find 'hooks' in my code that I can invoke async methods. I know that event handlers are the typical places (where IoC happens), but imagine the following scenario:

I want to start background task when a ViewController is loaded (as opposed to when a button is pressed).

async Task PerformMyTaskAsync ()
{
    // ...
    await ... // another async API
    // ...
}

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();

    // .. initialize UI
    await PerformMyTaskAsync ();
}

Obviously I can't await for PerformMyTaskAsync in ViewDidLoad because ViewDidLoad is neither an async method nor an event handler.

What is the 'alternative' approach to start a background task when a view controller loads (or appears, whatever) ?

like image 912
Eduardo Coelho Avatar asked Aug 16 '13 00:08

Eduardo Coelho


1 Answers

The newest Xamarin Stable Channel releases support Async/Await overloads for ViewController Lifecycle methods. Try:

public async override void ViewDidLoad()
like image 52
kwcto Avatar answered Sep 22 '22 08:09

kwcto