载入图片螺纹与WPF [英] Loading image in thread with WPF

查看:177
本文介绍了载入图片螺纹与WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使该显示来自互联网的图片列表框。通过结合的ItemSource到包含图像的URL和某些其它性质(标题,内容描述等...)的模式中提供的项目

I'm trying to make a listbox that display pictures from internet. The items are provided by binding itemsource to a model that contain the URL of the image and some other properties (title, desc, etc...).

不幸的是,列表加载,因为WPF试图显示列表之前从网上下载的所有照片非常缓慢,这让15至25秒申请冻结。

Unfortunately, the list is very slow to load because WPF is trying to download all pictures from the web before showing the list and it makes the application freeze for 15 to 25 sec.

我读过我应该载入的图片在其他线程,但我不知道我应该这样做,以及如何?它是更好地直接加载的所有照片模式(通过创建仅适用于一个线程池 - 但问题是,这是不是真正的模型/模型视图的一部分),或者是说最好创建一个后台线程,将直接更新当有数据列表?

I've read that I should load the picture in an other thread but I don't know where I should do it and how ? Is it better to load all pictures directly in the model (by creating a thread pool only for that - but the problem is that it's not really part of the model/modelview) or is that better to create a background thread that will update directly the list when it has data ?

谢谢!

推荐答案

最简单的办法是只刚刚设置的 Binding.IsAsync 属性是这样的:

The easy way is to just just set the Binding.IsAsync property like this:

<Image ImageSource="{Binding propertyThatComputesImageSource, IsAsync=true}" />



propertyThatComputesImageSource 每次访问都将被从做一个线程池线程。如果线程创建与ImageCacheOptions.OnLoad的形象,它会阻止,直到图像加载。因此,UI将立即启动,图像会在后台加载并可用时出现。

Each access to propertyThatComputesImageSource will be done from a ThreadPool thread. If the thread creates the image with ImageCacheOptions.OnLoad, it will block until the image is loaded. So the UI will start up immediately and images will be loaded in the background and appear when they are available.

Binding.IsAsync 是十年或者二形象一个很好的解决方案,但可能不是一个很好的解决方案,如果你有上百张图片和负载延时长,因为你可以与数百个线程的结束。在这种情况下,完全通过直接使用线程池加载数据绑定之外图片:

Binding.IsAsync is a good solution for ten or twenty images, but is probably not a good solution if you have hundreds of images and the load delay is long, since you could end up with hundreds of threads. In that case, load the images outside of databinding entirely by using ThreadPool directly:

ThreadPool.QueueUserWorkItem((state) =>
{
  foreach(var model in _models.ToArray())
    model.ImageSource = LoadOneImage(model.ImageUrl);
});

这可能需要一个或两个Dispatcher.Invoke延长,如果模型的属性的DependencyProperty,因为它们不能从一个单独的线程访问。

This may need to be extended with a Dispatcher.Invoke or two if the model's properties are DependencyProperty, since they can't be accessed from a separate thread.

此技术可以扩展到产卵工人固定数量的加载图像,并打破工作起来他们这么多之间图像下载正在发生,但同时下载的数量是有限的,所以你不要有数百个线程的结束。

This technique can be extended to spawn a fixed number of workers to load images and break the work up between them so multiple image downloads are happening, but the number of simultaneous downloads is limited so you don't end up with hundreds of threads.

这篇关于载入图片螺纹与WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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