Should be able to load bitmaps in non-UI threads
See original GitHub issueProposal: Should be able to load bitmaps in non-UI threads
Summary
We should be able to load bitmaps in non-UI threads. I’m talking about BitmapImage and WriteableBitmap classes.
Rationale
Forcing loading of bitmaps in the UI thread is a huge bottleneck when you need to deal with hundreds of bitmaps.
I completely understand forcing drawing the bitmaps only in the UI thread, but just loading them should not be bound in the UI thread.
Important Notes
Simply doing var bmp = new BitmapImage();
on a non UI thread throws an exception. This should not be the case. This piece of code should work:
Task.Run(async () => {
var root = ApplicationData.Current.LocalFolder.Path + "\\test.png";
var bmp = new BitmapImage();
var file = await StorageFile.GetFileFromPathAsync(root);
var stream = await file.OpenAsync(FileAccessMode.Read);
bmp.SetSource(stream);
});
Or, give me an equivalent, like, static BitmapImage BitmapImage.LoadFromStream(...)
.
For WriteableBitmap
, again, doing var bmp = new WriteableBitmap(100, 100);
on a non-UI thread will throw an exception. Should not be the case.
Executing the following in a non-UI thread should work.
public static BitmapSource soft_bmp_to_bmp(SoftwareBitmap soft_bmp) {
release.assert(soft_bmp != null);
WriteableBitmap bmp = new WriteableBitmap(soft_bmp.PixelWidth, soft_bmp.PixelHeight);
soft_bmp.CopyToBuffer( bmp.PixelBuffer);
return bmp;
}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:8
- Comments:6
Top GitHub Comments
As mention in the
Optimize Image Resources
section here https://docs.microsoft.com/en-gb/windows/uwp/debug-test-perf/optimize-animations-and-media#optimize-image-resources , decoding is actually already done off the UI thread even if you create the BitmapImage itself on the UI thread, as long as you use SetSourceAsync(…)To preserve XAML optimisations you should also make sure the BitmapImage is in the UI tree before calling SetSourceAsync, to make sure the image is decoded at a preferred resolution for it’s target display area.
@codenone Sorry for the late reply. It would be really useful to allow SetSourceAsync from a non-UI thread. This way, I don’t have to call into the UI thread, while caching bitmaps.
Agreed 100%. Personally, I think loading bitmaps in non-UI thread pretty much means I’ll add them to the UI programmatically, not via XAML.
Also , please don’t forget about WriteableBitmap 😃