San*_*ann 2 c# android asynchronous async-await xamarin
在Xamarin项目中,Android - 我是android开发的新手.在处理活动时,在OnCreate方法中为a设置自定义适配器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;
}
Run Code Online (Sandbox Code Playgroud)
在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();
}
Run Code Online (Sandbox Code Playgroud)
由于Getproducts是异步调用,因此它将异步加载数据.
问题是,一旦我将适配器设置为列表,它将尝试调用GetView适配器的方法.那时,不会加载项目.所以有一个空的例外.
如何处理这种情况.
谢谢.
您不能await在构造函数中使用.
你可以做几件事.这里最好的IMO是一个单独的异步方法,您可以在创建对象后调用并等待.
var listAdapter = new CustomListAdapter(this);
await listAdapter.InitializeAsync();
Run Code Online (Sandbox Code Playgroud)
另一种选择是使构造函数为私有,并具有一个异步静态方法,用于创建实例并对其进行初始化:
public static async Task<CustomListAdapter> CustomListAdapter.CreateAsync(Activity context)
{
var listAdapter = new CustomListAdapter(context);
listAdapter.items = await GetProductList();
return listAdapter;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1257 次 |
| 最近记录: |