简体   繁体   English

异步下载无效,同步下载有效

[英]Async download doesn't work, sync download does

The issue is that syncronous calls work but the async does not. 问题是同步调用有效,但异步无效。

Sync call: 同步通话:

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

Async call: 异步调用:

LoadNewsItemImageAsync (imgNewsItem, item.Image);

Async functionality: 异步功能:

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

The below function works when it is not run via an async task 以下功能在未通过异步任务运行时起作用

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

In general, you should not use Task.Run to create asynchronous wrappers for synchronous methods . 通常, 您不应使用Task.Run为同步方法创建异步包装器

In this particular instance, I believe you're running into a problem because Bitmap is a UI-affine type. 在这种特定情况下,我相信您会遇到问题,因为Bitmap是一种UI仿射类型。 Bitmap acts just like a UI control; Bitmap行为就像UI控件一样。 you should only access it from the UI thread. 您只能从UI线程访问它。

Consider this implementation of GetImageBitmapFromUrlAsync instead: 请考虑以下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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM