【问题标题】:Converting a download function to be async将下载功能转换为异步
【发布时间】:2014-06-16 06:14:23
【问题描述】:

我正在使用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;
}

有人可以帮我把这段代码设为异步吗?

提前致谢

【问题讨论】:

  • 您的 Xamarin.Android 版本是多少? 4.8+还是4.8以下?
  • 我的 Xamarin.Android 版本是 4.8+

标签: android asynchronous xamarin android-bitmap webclient


【解决方案1】:

您可以将Async / AwaitWebClientDownloadDataTaskAsync 方法一起使用,以使您的代码与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;    
}

【讨论】:

    【解决方案2】:

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

    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
        }
    }
    

    => 其他信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 2015-06-25
      • 1970-01-01
      相关资源
      最近更新 更多