Search code examples
async-awaitmvvmcross

MvvmCross ViewModel Start method async behavior clarification


In my ViewModel I load data in (overrided) Start method, like so:

    public override async void Start()
    {
        base.Start();

        await ProcessItems();
        // or the following (no difference for Start method behavior)
        await ProcessItems().ConfigureAwait(false);
    }

However, it doesn't look like the await/async logic actually works with the method (I tested it with Android only, though). "Doesn't work" means that right after calling my awaitable ProcessItems all the rest of ViewModel pipeline is called (like Initialize, ViewCreated, ViewAppearing etc.) before the awaitable method actually finished work. Which brings up some further issues as the rest of methods expect the data initialization already finished.

So, what should I take into consideration here and how handle this situation.

Thanks!


Solution

  • The calling code can't await Start because it is returning void. Any exceptions being thrown in there are being swallowed. If the method returned Task or Task<T> then this would work as you expect. You pretty much never want to use async void except in an event handler. There is an MSDN article going further into detail as to why async void should be avoided.

    This problem is fixed in MvvmCross 5 and later where you would do this same kind of initialization in Task Initialize method in place of this void Start method.