3

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?

valdetero
  • 4,624
  • 1
  • 31
  • 46
pnavk
  • 4,552
  • 2
  • 19
  • 43
  • Bothers me too, but I redefine them as `async`. After all, `async` is not a part of the method signature. An internal caller only needs to know that it's a `void`. The `_initTask` trick IMO turns the flow into a mess and thus defeats the very purpose of async/await. Possibly related: http://stackoverflow.com/q/15522900/11683 – GSerg Oct 18 '16 at 22:15
  • 4
    Generally speaking, you want to execute and exit out of these `Creation` methods as soon as possible to get your application running. It is best to avoid running long operations before your application starts. However the use of `async` and `await` in these methods should be fine as long as you understand the potential risks of deadlocking. These items are supported in both Xamarin.Android and Xamarin.iOS, so they are available to use. – Jon Douglas Oct 18 '16 at 23:28
  • 1
    On this topic, there is some interesting information in the video here: https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Tip-1-Async-void-is-for-top-level-event-handlers-only starting around 8:20. It talks about async void for methods that are like event handlers - which is like these lifecycle methods. Great info on what to watch out for. – therealjohn Nov 10 '16 at 17:32

1 Answers1

0

I like this post on async/await best practices. The biggest problem imho is from exceptions not getting handled properly when encountering async void.

To answer your question: Is there a specific reason why you have to use await or maybe can you choose a different approach to solving your problem? If you can, great, if not, the "downside" should be negligible.

der_michael
  • 3,151
  • 1
  • 24
  • 43