[英]C# WPF change ImageSource Image on Thread
我正在尝试从运行时从另一个线程而不是main_UI一个线程在运行时使用映像更新ImageSource,但是由于某些原因,我一直在获取:
The calling thread cannot access this object because a different thread owns it.
我已经尝试了几件事:
im_Cover.Dispatcher.Invoke(() => { if (im_Cover.Source != image) im_Cover.Source = image; });
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { im_Cover.Source = image; }));
这是我的代码:
for (int i = 1; i < correctArtist.images.Count; i++)
{
if (correctArtist.images[i].width > correctArtist.images[biggest].width)
biggest = i;
}
Image biggestImage = correctArtist.images[biggest];
var imgUrl = biggestImage.url;
image = new BitmapImage(new Uri(imgUrl));
bool uiAccessCover = im_Cover.Dispatcher.CheckAccess();
if (uiAccessCover)
{
im_Cover.Source = image;
}
else
{
//im_Cover.Dispatcher.Invoke(() => { if (im_Cover.Source != image) im_Cover.Source = image; });
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { im_Cover.Source = image; }));
}
出于某种原因: lb_Song.Dispatcher.Invoke(() => { if ((string)lb_Song.Content != song) lb_Song.Content = song; });
确实有效。
知道为什么它不起作用以及如何解决这个问题吗?
在将BitmapImage从后台线程传递到UI线程之前,例如
im_Cover.Dispatcher.BeginInvoke(new Action(() => im_Cover.Source = image));
它必须被冻结。 否则,还必须在UI线程上创建它,例如
im_Cover.Dispatcher.BeginInvoke(new Action(() =>
im_Cover.Source = new BitmapImage(new Uri(imgUrl))));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.