1

我在 xamarin.forms 中为我的应用程序构建一个屏幕,该 caul 基于一个标签页,该标签页是根据我因使用服务而获得的对象列表动态构建的。在我调用该方法来使用带来列表的 API 之后,我需要根据它的某些数据通过它来填充一个可观察的视图模型集合,这将是选项卡。我遇到的问题是不知道怎么调用异步方式消费API的async方法,这样API的消费不会和遍历列表的操作冲突。然后是我的 ViewModel 的一小部分代码:

public MonitoringViewModel()
    {
        LoadThings();
        Tabs = new ObservableCollection<MonitoringTabsViewModel>();
        foreach (PcThing t in Things)
        {
            Tabs.Add(new MonitoringTabsViewModel(t.description));
        }
    }


    private async void LoadThings()
    {
        Things = new List<PcThing>(await App.WebApiManager.GetCustomerThinksAsync());
    }

我得到的是,在 xamarin 实时播放器中,应用程序在几秒钟后从绿色信号变为红色信号而没有显示任何内容,并且在它的日志中我得到这个: GetEnumerator 的目标为空(NullReferenceException)

4

2 回答 2

3

Since you are doing this in the constructor , I would try the following:

using System.Threading.Tasks;

The risk here is if you are not in control of the LoadThings completing, it can hang.

public MonitoringViewModel()
{
    var task = Task.Run(async () => { await LoadThings();}
    Task.WaitAll(task); //block and wait for task to complete
于 2018-11-18T22:55:40.440 回答
1
public async Task<List<PcThing>> LoadThings()
{
    return await App.WebApiManager.GetCustomerThinksAsync();
}

在你的 ViewModel

Things = LoadThings().GetAwaiter().GetResult();
于 2018-11-18T21:03:06.683 回答