C# / MonoTouch: how to call an async method when a ViewController is created/appears
async-await, c#, xamarin, xamarin.ios
Solution
The newest Xamarin Stable Channel releases support Async/Await overloads for ViewController Lifecycle methods. Try:
public async override void ViewDidLoad()
Problem
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) ?