How to load file icons in a background thread [WPF]
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.
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).
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.
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;
}
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.
精彩评论