我试图从Web服务器上获取很多图像,所以为了不使服务器每秒过载数百个请求,我只允许通过WebService处理其中的几个请求。以下代码位于保存图像的对象以及所有绑定(bind)的位置。
ThreadStart thread = delegate()
{
BitmapImage image = WebService.LoadImage(data);
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
this.Image = image;
}));
};
new Thread(thread).Start();
图像加载得很好,图像加载时UI流畅运行,但是从不调用
this.Image = image
。如果我使用Dispatcher.CurrentDispatcher.Invoke(..)
,则该行被调用,但不适用于设置Image。调度员为什么不调用我的 Action ?
最佳答案
由于您是在工作线程上创建BitmapImage
的,因此它不属于WPF线程。
也许这段代码可以帮助您解决问题:
您发布的代码
ThreadStart thread = delegate()
{
BitmapImage image = WebService.LoadImage(data, Dispatcher.CurrentDispatcher);
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
this.Image = image;
}));
};
new Thread(thread).Start();
如何更改
WebService.LoadImage
以使其“起作用” BitmapImage LoadImage(object data, Dispatcher dispatcher)
{
// get the raw data from a webservice etc.
byte[] imageData = GetFromWebserviceSomehow(data);
BitmapImage image;
// create the BitmapImage on the WPF thread (important!)
dispatcher.Invoke(new Action(()=>
{
// this overload does not exist, I just want to show that
// you have to create the BitmapImage on the corresponding thread
image = new BitmapImage(imageData);
}));
return image;
}