0

I tried to use mvvmlight as my mvvm model but there some error I don't understand. It said I cant void cant use await. If void cant use await then what should I do in here here is my code:

async void OnLoginButtonClicked(object sender)
{
    try
    {
        var result = await App.AuthenticationClient.AcquireTokenAsync(
            Constants.Scopes,
            string.Empty,
            UiOptions.SelectAccount,
            string.Empty,
            null,
            Constants.Authority,
            Constants.SignUpSignInPolicy);
        await _navigationservice.NavigateTo(Locator.MainPageViewModel);
    }
    catch (MsalException ex)
    {
        if (ex.Message != null && ex.Message.Contains("AADB2C90118"))
        {
            await OnForgotPassword();
        }
        if (ex.ErrorCode != "authentication_canceled")
        {
            //  await DisplayAlert("An error has occurred", "Exception message: " + ex.Message, "Dismiss");
        }
    }
}

and the error is in the await _navigationservice.NavigateTo(Locator.MainPageViewModel); it shows error message right this Cannot await 'void' what should I do here?

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Theodorus Agum Gumilang
  • 1,414
  • 4
  • 23
  • 46

1 Answers1

1

Put void returning method inside Task.Run() and await it. Here you find better explanation. Do you have to put Task.Run in a method to make it async?

You can implement like this.

async void OnLoginButtonClicked(object sender)
{
    try
    {
        ....//previous code
        await Task.Run( () =>
          {
            _navigationservice.NavigateTo(Locator.MainPageViewModel);
          });
    }
    catch (MsalException ex)
    {

        //
    }
}
JharPaat
  • 321
  • 1
  • 2
  • 12
  • Keep in mind that any code inside the `Action` passed to `Task.Run` will run on the `ThreadPool`. This has repercussions when the code needs to access the UI. – Bradley Uffner Sep 28 '17 at 13:24