繁体   English   中英

C#WPF在线程上更改ImageSource图像

[英]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; }));
  • 冻结图像(这是不可能的)。 我尝试在错误上添加一个消息框,一旦错误出现并按OK,由于某种原因,图像确实加载了。
  • 使用自定义下载完成的事件处理程序进行了尝试,该事件处理程序甚至没有触发。

这是我的代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM