将下载功能转换为异步

时间:2014-06-16 06:14:24

标签: android asynchronous xamarin android-bitmap webclient-download

我正在使用Xamarin,我正在为GridView下载许多图片。

以下是我为每张图片调用的代码:

private Bitmap GetImageBitmapFromUri(string uri)
{
    Bitmap imageBitmap = null;

    using (var webClient = new WebClient())
    {
        var imageBytes = webClient.DownloadData(uri);
        if (imageBytes != null && imageBytes.Length > 0)
        {
            imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
        }
    }

    return imageBitmap;
}

有人可以帮我把这段代码变成异步吗?

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以Async / Await使用WebClient DownloadDataTaskAsync方法将代码异步设为defined here with example

async Task<Bitmap> downloadAsync(object sender, System.EventArgs ea)
{
  WebClient webClient = new WebClient();
  var url = new Uri("http://photojournal.jpl.nasa.gov/jpeg/PIA15416.jpg");
  byte[] bytes = null;

  try{
    bytes = await webClient.DownloadDataTaskAsync(url);
  }
  catch(TaskCanceledException){
    // Exception
    return;
  }
  catch(Exception e){
    // Exception
    return;
  }

  Bitmap bitmap = await BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);

  return bitmap;    
}

答案 1 :(得分:0)

这是可以在JAVA中找到的等效C#AsyncTask:

public class DownloadBitmap : AsyncTask
{
    protected override void OnPreExecute()
    {
         //launch loading dialog.. before your main task
    }

    protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
    {
         //download your Bitmap
    }

    protected override void OnPostExecute(Java.Lang.Object result)
    {
         //return your Bitmap to update the UI
    }
}

=&GT;其他信息here