如何预加载在后台线程中的图片? [英] how to preload images in a background thread?

查看:100
本文介绍了如何预加载在后台线程中的图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的WPF应用程序,我需要加载一些图像。我只需要一次显示一个图像。如果在需要时我加载图片,有一个稍微延迟。所以,我心想:嘿,为什么不去做一些在后台线程中预加载不能那么难?。我有螺纹的一些经验,但还不足以知道,这个想法是错误的。我开始编程和遇到的一些问题。我固定的一些问题,我可能可以解决其他问题了,但是这将导致意大利面条代码。所以,我觉得从白手起家将是最好的。什么最初刨需要建立一个很好的和小预压线? ?是否有一个模式或类似的东西。

In my WPF app i need to load some images. I only need to display one image at a time. If i load the image when it's needed, there is a slightly delay. So i thought to myself: "Hey, why not do some preloading in a background thread? Can't be that hard." I have some experience with threads, but not enough to know that this thought was wrong. I started programming and run into some problems. I fixed some of the problems and i probably could fix the other problems too, but that would result in spaghetti code. So, I think starting from the scratch would be the best. What initial planing is needed to build a nice and little preloading thread? Is there a pattern or something like that?

下面是我的当前设置:


  • 的LinkedList<串> 来店pathes的图片和导航到下一个画面

  • 词典<字符串,BitmapImage的> 来存储预装的图像

  • LinkedList<string> to stores pathes to the pictures and navigate to the next picture
  • Dictionary<string, BitmapImage> to store the preloaded images

推荐答案

我D使用是这样的:

class ImageManager
{
  private Dictionary<string, Image> images=
    new Dictionary<string,Image>();

  public Image get(string s) {  // blocking call, returns the image
    return load(s);
  }

  private Image load(string s) {  // internal, thread-safe helper
    lock(images) {
      if(!images.ContainsKey(s)) {
        Image img=// load the image s
        images.Add(s,img);
        return img; 
      }
      return images[s];
    }
  }

  public void preload(params string[] imgs) {  // non-blocking preloading call
    foreach(string img in imgs) { 
      BackgroundWorker bw=new BackgroundWorker();
      bw.DoWork+=(s,e)=>{ load(img); }  // discard the actual image return
      bw.RunWorkerAsync();
    }
  }
}

// in your main function
{
   ImageManager im=new ImageManager();
   im.preload("path1", "path2", "path3", "path4"); // non-blocking call

   // then you just request images based on their path
   // they'll become available as they are loaded
   // or if you request an image before it's queued to be loaded asynchronously 
   // it will get loaded synchronously instead, thus with priority because it's needed
}

这篇关于如何预加载在后台线程中的图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆