【问题标题】:How to handle async & await with default override's如何使用默认覆盖处理异步和等待
【发布时间】:2015-05-26 13:53:09
【问题描述】:

在 Xamarin 项目中,Android - 我是 android 开发新手。在处理活动时,在OnCreate 方法中为ListView 设置自定义适配器。

protected async override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);
    SetContentView(Resource.Layout.Main);

    var listAdapter = new CustomListAdapter(this);
    //.................................................
    listView = (ListView) FindViewById(Resource.Id.list);

    // populate the listview with data
    listView.Adapter = listAdapter;
}

在适配器的ctor 中,创建异步调用中的项目列表。

public CustomListAdapter(Activity context) //We need a context to inflate our row view from
    : base()
{
    this.context = context;
    // items is List<Product>
    items = await GetProductList();
}

由于 Getproducts 是异步调用,它会异步加载数据。

问题是一旦我将适配器设置为列表,它将尝试调用适配器的GetView 方法。届时,将不会加载项目。所以有一个空异常。

如何处理这种情况。

谢谢。

【问题讨论】:

标签: c# android asynchronous xamarin async-await


【解决方案1】:

你不能在构造函数中使用await

您可以做几件事。 IMO 最好的方法是有一个单独的异步方法,您可以在创建对象后调用并等待。

var listAdapter = new CustomListAdapter(this);
await listAdapter.InitializeAsync();

另一种选择是将构造函数设为私有,并使用异步静态方法创建实例并对其进行初始化:

public static async Task<CustomListAdapter> CustomListAdapter.CreateAsync(Activity context)
{
    var listAdapter = new CustomListAdapter(context);
    listAdapter.items = await GetProductList();
    return listAdapter;
}

【讨论】:

  • 你打败了我! :D 所以我赞成你的。
  • 此外,适配器构造函数可能不是加载内容的最佳位置。我将从 OnCreate() listAdapter.AddAll(await GetProductList()); 填充适配器
  • 我在适配器中看不到 InitializeAsync 方法。这个方法是从哪个基础实现的?
  • @Sankarann 这不是现有的方法。这个想法是你把你想要在构造函数中做的事情放到一个异步方法中,这样你就可以调用它并等待返回的任务。
【解决方案2】:

可能会覆盖 getCount,因此如果 items 仍然为 null 或 items 有零个项目,则返回 listView 大小应为 0。

public int getCount() {
    return items != null ? items.size() : 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多