异步下载不起作用,同步下载

时间:2014-04-03 07:53:08

标签: c# android asynchronous bitmap xamarin

问题在于同步调用有效,但异步调用没有。

同步通话:

using (var bmp = GetImageBitmapFromUrl (item.Image))
{
    imgNewsItem.SetImageBitmap (bmp);
    bmp.Dispose ();
}

异步通话:

LoadNewsItemImageAsync (imgNewsItem, item.Image);

异步功能:

public async void LoadNewsItemImageAsync(ImageView v, string url)
{
    using (Bitmap bmp = await GetImageBitmapFromUrlAsync(url))
    {
        v.SetImageBitmap (bmp);
        bmp.Dispose ();
    }
}

Task<Bitmap> GetImageBitmapFromUrlAsync (string url)
{
    return Task.Run<Bitmap>(() => GetImageBitmapFromUrl (url));
}

以下功能在不通过异步任务运行时起作用

Bitmap GetImageBitmapFromUrl(string url)
{
    Bitmap imageBitmap = null;
    try {
        using (var webClient = new WebClient())
        {
            var imageBytes = webClient.DownloadData(url);
            if (imageBytes != null && imageBytes.Length > 0)
            {
                imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, 
                    imageBytes.Length);
            }
    } catch (Exception ex) {
        Log.WriteLine (LogPriority.Error, "GetImageFromBitmap Error", ex.Message);
    }

    return imageBitmap;
}

1 个答案:

答案 0 :(得分:0)

一般来说,you should not use Task.Run to create asynchronous wrappers for synchronous methods

在这个特定的例子中,我认为你遇到了一个问题,因为Bitmap是一个UI仿射类型。 Bitmap就像一个UI控件;你应该只从UI线程访问它。

请考虑GetImageBitmapFromUrlAsync的这种实现:

async Task<Bitmap> GetImageBitmapFromUrlAsync(string url)
{
  Bitmap imageBitmap = null;
  try {
    using (var webClient = new WebClient())
    {
      var imageBytes = await webClient.DownloadDataTaskAsync(url);
      if (imageBytes != null && imageBytes.Length > 0)
      {
        imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, 
            imageBytes.Length);
      }
  } catch (Exception ex) {
    Log.WriteLine (LogPriority.Error, "GetImageFromBitmap Error", ex.Message);
  }

  return imageBitmap;
}