Xamarin形式:调试器无需等待就离开了异步方法

时间:2019-05-06 15:02:39

标签: c# xamarin xamarin.forms async-await

我开始使用XamarinForms,但是遇到了 strange 问题。

应用流程如下:

  • 从页面(NewExpensePage.cs)中打开创建操作的模式(推送异步)
  • 页面具有BindingContext和ViewModel (ExpenseViewModel.cs)
  • 按钮命令与ViewModel类中的命令(SaveExpenseCommand)连接,该命令将调用服务(IBTService.cs)中的方法,服务将依次发出HttpPost请求。

后面的页面代码:

public partial class NewExpensePage : ContentPage
{
    private readonly ExpenseViewModel viewModel;

    public NewExpensePage(int currentGroupId)
    {
        InitializeComponent();
        viewModel = new ExpenseViewModel(currentGroupId);
        this.BindingContext = viewModel;
        // let this page know save op has completed, and the close the modal
        MessagingCenter.Subscribe<ExpenseViewModel>(this, "save-completed", async (i) => { await Navigation.PopModalAsync(); });
    }
}

ViewModel代码:

public class ExpenseViewModel : BaseViewModel
{
    /* ... */
    public Command SaveExpenseCommand { get; set; }
    private readonly int CurrentGroupId;
    public ExpenseViewModel(int selectedGroupId)
    {
        CurrentGroupId = selectedGroupId;
        this.LoadCategoriesCommand = new Command(async () => await LoadCategories());
        this.SaveExpenseCommand = new Command(async () => await SaveExpense());
    }

    async Task SaveExpense()
    {
        Item.ExpenseCategoryId = SelectedCategory.Id;
        await IBTService.SaveExpense(Item);
        MessagingCenter.Send(this, "save-completed");
    }
}

最后是服务代码(IBTService.cs)中的方法:

    public async Task<bool> SaveExpense(Expense model)
    {
        using (var httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri(api);
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

            var dbModel = new ApiExpense
            {
                Amount = model.Amount,
                Date = model.Date.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture),
                ExpenseCategoryId = model.ExpenseCategoryId,
                Description = model.Description
            };
            // HERE: Debugger runs out to caller method (back in view model) without waiting for this to complete
            var response = await httpClient.PostAsync("api/Expenses/PostExpense", new StringContent(JsonConvert.SerializeObject(dbModel)));
            if (response.IsSuccessStatusCode)
            {
                return true; //temp solution
            }

            return false;
        }
    }

这里的问题始于最终代码部分中的var response = await httpClient.PostAsync...,调试器在执行这一行时就跳出了执行程序,而没有 *等待 >完成此结果。

任何帮助将不胜感激!

0 个答案:

没有答案
相关问题