我发现很难解决非常简单的任务:如何从我的远程服务器下载映像?
最简单的方法就是:
BitmapImage img = new BitmapImage(new Uri("http://myserv/test.jpg", UriKind.Absolute));
xamlImageContainer.Source = img;但是我认为这个解决方案并不理想,因为它可以阻止UI线程(可以吗?)因此,我决定使用“异步”方法:
async void LoadImage()
{
xamlImageContainer.Source = await Task.Run(() =>
{
return new BitmapImage(new Uri("http://myserv/test.jpg", UriKind.Absolute));
});
}但是在return new BitmapImage这条线上,我得到了UnauthorizedAccessException,上面写着“无效的跨线程访问”!这里有什么问题,请提出建议。
发布于 2013-10-10 08:00:19
BitmapImage类型的对象只能在UI线程中装箱。因此出现了“无效的跨线程访问”。
但是,您可以将BitmapImage的CreateOptions属性设置为BackgroundCreation。这样,图像就可以在后台线程中下载和解码:
img.CreateOptions = BitmapCreateOptions.BackgroundCreation;发布于 2015-01-15 15:36:41
是的@anderZubi是正确的。但是,如果您想从后台线程加载某个内容到UI线程,CreateOptions是解决此问题的最佳解决方案。你得给调度员打电话。Dispatcher.BeginInvoke(() => YourMethodToUpdateUIElements());
这将调用UI线程上的方法,而不会得到AccessViolationException。
只是一场比赛。
https://stackoverflow.com/questions/19284591
复制相似问题