如何在后台线程中加载文件图标 [WPF]

发布于 2024-08-08 21:23:13 字数 309 浏览 2 评论 0原文

我的代码提取文件图标(甚至拇指)。但是,如果我有很多文件,可能需要一段时间。我尝试使用后台线程来加载图标。

  1. 从图标提取的表单文件创建的位图并存储在列表中。似乎对于每个本机位图,它处理仅存在于所有者线程中(即创建位图的线程中)。

  2. 在 UI 线程中从这些本机创建 WPF 位图。

所以问题是我不知道如何在 UI 线程中使用在后台线程中创建的位图。

-- 或 --

2b.在后台线程中创建 wpf 位图并在 UI 线程中使用它们

但问题完全相同。

my code extracts file icons(or even thumbs). however if i have many files it may take a while. I've tried to use background thread to load icons.

  1. Bitmap created from icon extracted form file and stored in list. It seems that for each native bitmap it handle exist only in owner thread (that is in thread where bitmap created).

  2. In UI thread create WPF bitmaps from those native.

So the problem is that i don't know how to use bitmaps created in background thread in UI thread.

-- or --

2b. Create wpf bitmap in background thread and use them in UI thread

But the problem is exactly the same.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

葮薆情 2024-08-15 21:23:13

您只需在加载图像后将其冻结即可。冻结对象是只读的,可以安全地跨线程使用。例如 :

private void _backgroundWorkerLoadImage_DoWork(object sender, DoWorkEventArgs e)
{
    BitmapImage img = new BitmapImage();
    img.BeginInit();
    img.UriSource = imageUri;
    img.EndInit();
    img.Freeze();
    e.Result = img;
}

void _backgroundWorkerLoadImage_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var img = e.Result as ImageSource;
    imageControl.Source = img;
}

You just need to freeze the images after you load them. Frozen objects are read-only and safe to use across threads. For instance :

private void _backgroundWorkerLoadImage_DoWork(object sender, DoWorkEventArgs e)
{
    BitmapImage img = new BitmapImage();
    img.BeginInit();
    img.UriSource = imageUri;
    img.EndInit();
    img.Freeze();
    e.Result = img;
}

void _backgroundWorkerLoadImage_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var img = e.Result as ImageSource;
    imageControl.Source = img;
}
坐在坟头思考人生 2024-08-15 21:23:13

如果我理解您正在做什么,那么提高性能的一种方法可能是在读取文件图标的过程中引入一些智能。

考虑这样的情况:目录中有大量 .DOC 文件,并且读取所有这些文件的文件图标没有多大意义。

您将拥有已读取的文件图标的缓存,因此无需读取每个 .DOC 文件的文件图标。这里需要权衡将图像保存在内存中,但您应该能够在性能和使用过多内存之间找到一个令人满意的折衷方案。

If I understand what you are doing correctly, one way to improve performance might be to introduce some intelligence into the process which is reading the file icons.

Consider the situation in which there are lots of .DOC files in a directory and there isn't much point in reading the file icon for all of them.

You would have a cache of file icons which have been read already instead so it wouldn't be necessary to read the file icon for each of the .DOC files. There is a trade off here for holding the images in memory but you should be able to get a happy medium between performance and using too much memory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文