在GridView适配器中使用异步方法GetView方法

问题描述:

我正在编写一个Xamarin Android应用程序,并且我有一个关于GridView适配器的问题。在GridView适配器中使用异步方法GetView方法

是否可以使用async关键字和GetView方法?我有一个await函数,我希望在GetView方法中使用,该方法为每个GridView项目异步检索图像?

目前的方法是:

public override View GetView (int position, View convertView, ViewGroup parent) 

我要寻找的东西相当于:

public async override Task<View> GetView (int position, View convertView, ViewGroup parent) 

不过,我得到这个错误:

'SimpleMapDemo.GridViewWithImageAndTextAdapter.GetView(int, Android.Views.View, Android.Views.ViewGroup)': return type must be 'Android.Views.View' to match overridden member 'Android.Widget.BaseAdapter.GetView(int, Android.Views.View, Android.Views.ViewGroup)' 

这可能吗?如果不是,是否可以在每个GetView方法中启动后台进程以异步检索所需的图像,还是应该尝试其他方法?

在此先感谢

不能使用等待,因为你必须从UI线程访问UI因此它没有意义使用异步方法。没有这样的方法。

这就是说你提到的另一种选择是要走的路。在这里,请参阅我的答案Image is assigned to another row item of ListView

+0

你,你链接到对方的回答比使用'ContinueWith'好得多。 – EvilTak 2016-05-30 07:57:30

您可以随时在您的等待方法中使用ContinueWith()(只要它返回Task)。

... 
YourMethod().ContinueWith(t => 
    { 
     //Whatever you need to execute when YourMethod() finishes 
    }); 
... 

这里的more infoContinueWith()

你可以运行你的任务是这样的:

Task.Run(async delegate() => { 
     await AsyncMethod().ContinueWith(() => { 
      Context.InvokeOnMainThread(() => { 
       //DO YOUR UI STUFF HERE!! 
       }); 
     }); 
});