图片加载在C#中的异步 [英] Loading Images asynchronous in C#
问题描述
我正在它加载大量的图片,并将其显示为缩略图一个C#WPF应用程序。我希望做一个多线程的方式。因此,我试图执行一个BackgroundWorker。
I'm working on a C# WPF application which loads a lot of images and displays it as thumbnails. I'd like to do it in a multi-threaded way. Therefore I tried to implement a BackgroundWorker.
BackgroundWorker的的DoWork的的code():
The code of the BackgroundWorker's DoWork():
string[] files = e.Argument as string[];
foreach (string file in files)
{
ImageModel image = new ImageModel();
image.FilePath = file;
_importWorker.ReportProgress(1, image);
_imageCollectionVM.Images.Add(image); // also tried this one in ReportProgress()
}
在我的XAML code我绑定到ImageModel的BitmapImage的财产。 (AsyncState = TRUE于事无补。)在这里,我得到这个错误:DependencySource和的DependencyObject必须在同一个线程
In my XAML code I bind to the BitmapImage property of ImageModel. (AsyncState=True doesn't help.) Here I get this error: "DependencySource" and "DependencyObject" have to be in the same thread.
<Image Source="{Binding BitmapImage}" />
如果我评论了这一点,形象似乎是进口的,但我不能访问它,例如在一个ListView选择它。在它的SelectionChanged它,然后说,这对象被另一个线程拥有。
If I comment this out, the image seems to be imported but I cannot access it, e.g. by selecting it in a ListView. In its SelectionChanged it says then that this object is possessed by another thread.
我该如何解决这些问题?在此先感谢!
How do I solve these problems? Thanks in advance!
推荐答案
后台工作是大型任务伊莫好,但如果是一些简单的像你正在做的我会preFER做这样的东西。
BackGround Worker is good imo for large tasks, but if it something simple like what you are doing I would prefer to do it like this
开始用图片列表
List<Image> Images =new List<Image>();
然后运行该
Task.Factory.StartNew( () =>
{
string[] files = e.Argument as string[];
foreach (string file in files)
{
ImageModel image = new ImageModel();
image.FilePath = file;
// _importWorker.ReportProgress(1, image);
this.BeginInvoke( new Action(() =>
{
Images.Add(image);
}));
}
});
没有保证我有括号在code中的权数。
No guarantee I have the right number of brackets in that code.
这篇关于图片加载在C#中的异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!