我有一些代码可以在后台加载一个BitmapImage,冻结它,然后将它发送到UI线程。但是,即使没有发送到UI线程,将JPG加载到BitmapImage中的操作也会导致UI卡顿,即使它发生在后台线程上。
在阅读有关BitmapImage的文章时,似乎情况可能是这样的,即使在后台线程中,BitmapImage也将使用Dispatcher,因此至少会在UI线程中运行其加载过程的一部分。
这对我的动画能力来说是个坏消息,因为它在后台加载图像时会卡顿和停滞。就我的代码而言,在UI线程中唯一要运行的就是将图像的“Source”属性设置为BitmapImage。
那么,简单的问题是,如何在不接触UI线程的情况下将JPG加载到BitmapImage中?
BitmapImage bi = null;
bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(path, UriKind.Absolute);
bi.DecodePixelWidth = 250;
bi.EndInit();
bi.Freeze();
(recv as UIElement).Dispatcher.Invoke(new Action(() =>
{
Debug.WriteLine(path + " GOT IMAGE FROM IMAGE");
recv.recieveBitmap(bi);
}), DispatcherPriority.Input);
Action a = () => processImage(p);
Task t = new Task(a);
_jobs.Add(t);
t.Start();发布于 2015-05-11 17:31:07
在后台线程中加载BitmapImage的更有效的方法可能是从FileStream加载它,而不是设置它的UriSource属性。
var bi = new BitmapImage();
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
bi.BeginInit();
bi.DecodePixelWidth = 250;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = stream;
bi.EndInit();
}
bi.Freeze();https://stackoverflow.com/questions/30162446
复制相似问题