2013-10-09 105 views
0

我發現很難解決很簡單的任務:如何從我的遠程服務器下載圖像?正確的方式下載圖像Windows Phone 8

做到這一點最簡單的方法就是:

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它說「無效的跨線程訪問」! 這裏有什麼問題,請建議。

回答

1

BitmapImage類型的對象只能在UI線程中創建。因此,「無效的跨線程訪問」。

但是,您可以將BitmapImageCreateOptions屬性設置爲BackgroundCreation。這樣圖像在後臺線程下載並解碼:

img.CreateOptions = BitmapCreateOptions.BackgroundCreation; 
+0

我接受你的答案,因爲它似乎工作。當像這樣使用BitmapImage內部創建一些後臺線程? –

+1

顯然是的。在這裏看到文檔:http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.windows.media.imaging.bitmapcreateoptions(v=vs.105).aspx – anderZubi

1

是@anderZubi是正確的。但是,CreateOptions是解決此問題的最佳解決方案,如果您想要將某些內容從後臺線程加載到UI線程中。你需要調用分派器。 Dispatcher.BeginInvoke(()=> YourMethodToUpdateUIElements());

這將調用UI線程上的方法,您將不會得到AccessViolationException。

只是FYI。