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) ?
The newest Xamarin Stable Channel releases support Async/Await overloads for ViewController Lifecycle methods. Try:
public async override void ViewDidLoad()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With