2016-10-01 16 views
0

这里是我的一些代码:尝试将图像设定为在分派器图像控制使得误差

var dispatcher = this.Dispatcher; 
new Task(new Action(delegate 
{ 
    BitmapImage bi = new BitmapImage(); 
    //...code for loading image 
    Action updateImage =() => { this.picCover.Source = bi; }; 
    Dispatcher.BeginInvoke(updateImage); 
})).Start(); 

picCover是一个图像小部件。 Here Dispatcher.BeginInvoke(updateImage);我得到System.InvalidOperationException:调用线程不能访问这个对象,因为不同的线程拥有它。 我也尝试将this.Dispatcher更换为picCover.Dispatcher,但它不起作用。

回答

0

你没有说是什么错误,但如果我不是错了,它是

必须在相同的线程创建DependencySource作为DependencyObject的

如果这是这种情况,因为BitmapImage本身一个DispatcherObject所以它关系到你创建它的线程以及你想使用它的线程。您需要Freeze位图图像,因为它是在不同的线程

BitmapImage bi = new BitmapImage(); 
//...code for loading image 

bi.Freeze(); 

Action updateImage =() => { this.picCover.Source = bi; }; 
Dispatcher.BeginInvoke(updateImage); 
+0

谢谢。但是编译器显示“这个Freezable不能被冻结”。然后我处理了“下载完成”事件,但它永远不会被调用。 – Zhangzijing

+0

答案是在你家加载你的位图 – dkozl

0

创建我觉得你可以把这种方式:

async void Test() 
{ 
    var dispatcher = this.Dispatcher; 
    await dispatcher.InvokeAsync(() => { 
    BitmapImage bi = new BitmapImage(); 
    //...code for loading image 

    this.picCover.Source = bi; 
    }); 
} 
0

做这样的:

var dispatcher = this.Dispatcher; 
new Task(new Action(delegate 
{ 

    Action updateImage =() => { 

     BitmapImage bi = new BitmapImage(); 
     bi.BeginInit(); 
     bi.UriSource = new Uri("https://s-media-cache-ak0.pinimg.com/236x/c6/f2/7b/c6f27bf410ff72b91a7947ef5ee94f3d.jpg", UriKind.Absolute); 
     bi.EndInit(); 

     this.picCover.Source = bi; 

    }; 
    Dispatcher.BeginInvoke(updateImage); 
})).Start(); 
+0

我试过了。但是在加载图片时UI没有响应 – Zhangzijing

+0

@Zhangzijing我在发布之前测试了代码。 – AnjumSKhan

+0

也许你有一个高速网络。最后,我使用'WebClient'下载图像。并将返回的字节放入'MemoryStream'中,用'Stream'替换'new Uri(...)'。 – Zhangzijing

相关问题