WPF异步加载BitmapImage
当你在WPF主线程中时不时需要加载图片时,界面上的Animation会因为IO操作而卡壳,要想保持动画的流畅就必须将IO操作放到后台线程中操作,如下:
view sourceprint?01
private
?void
?ChangeImage() {
02
????
Image image =?
new
?Image();
03
?04
????
new
?Thread(
new
?ThreadStart(() => {
05
????????
BitmapImage bitmap =?
new
?BitmapImage();
06
????????
bitmap.BeginInit();
07
????????
bitmap.UriSource =?
new
?Uri(images[index++ % images.Count]);
08
????????
bitmap.CacheOption = BitmapCacheOption.OnLoad;
09
????????
bitmap.EndInit();
10
????????
bitmap.Freeze();
11
?12
????????
Dispatcher.BeginInvoke((Action)(() => {
13
????????????
image.Source = bitmap;
14
????????????
image.Stretch = Stretch.UniformToFill;
15
????????????
TransitionBox.Content = image;
16
????????
}));
17
?18
????
})).Start();
19
}