【问题标题】:Cannot Await Void in MVVM Light Xamarin Forms无法在 MVVM Light Xamarin 表单中等待 Void
【发布时间】:2018-03-10 02:44:21
【问题描述】:

我尝试使用 mvvmlight 作为我的 mvvm 模型,但出现了一些我不明白的错误。它说我不能取消不能使用等待。如果 void 不能使用 await 那么我应该在这里做什么是我的代码:

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");
        }
    }
}

错误在await _navigationservice.NavigateTo(Locator.MainPageViewModel); 它在Cannot await 'void' 右侧显示错误消息我应该在这里做什么?

【问题讨论】:

  • void 更改为 Task
  • 异步/等待的良好实践:msdn.microsoft.com/en-us/magazine/jj991977.aspx
  • 从`_navigationservice.NavigateTo`行中删除await。该方法无效,因此无法等待。
  • 你不能在任何地方等待void,不仅是在 Xamarin 应用程序中。

标签: c# asynchronous xamarin mvvm mvvm-light


【解决方案1】:

将 void 返回方法放入 Task.Run() 并等待它。 在这里你可以找到更好的解释。 Do you have to put Task.Run in a method to make it async?

你可以这样实现。

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

        //
    }
}

【讨论】:

  • 请记住,Action 中传递给Task.Run 的任何代码都将在ThreadPool 上运行。当代码需要访问 UI 时,这会产生影响。
猜你喜欢
  • 2015-05-21
  • 1970-01-01
  • 2020-07-10
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多