Most of the articles on async/await
best practices suggest that async void
methods should be avoided unless the method is an event handler.
What are the best practices for handling situations where you need to call an async method during initialization of a view?
I've seen code that marks lifecycle methods such as ViewDidLoad
, ViewWillAppear
, OnCreate
, OnResume
etc as async void so that a method can be await
-ed in the method body - but my gut reaction to this is that it is dangerous if the method is an override from the framework - since the consumer might not be aware of the context in which the method is being used internally.
An alternate approach could be to assign the result of the async
method to a Task
. Then await
that Task
before any dependent code runs:
Foo.cs:
async Task SomeMethodForInit()
{
//some code here for Init
}
Android Fragment:
Task _initTask;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
_initTask = fooInstance.SomeMethodForInit();
}
...
//call this before doing anything dependent on that task
await _initTask;
Is this the right approach?