var client = new WebClient();
var bytes = client.DownloadData(webUrl); <-- NOT null
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.StreamSource = new MemoryStream(bytes); <-- null
img.EndInit();
img_DownloadCompleted(img, webUrl);
}));
上述代碼在線程中執行以避免阻塞UI。來自封閉塊的變量在匿名函數中變爲空
我試圖從互聯網下載圖像到BitmapImage
對象。圖像正確下載,但是當我嘗試在我的UI中使用它時(使用Dispatcher.Invoke
),我收到以下錯誤消息:The calling thread cannot access this object because a different thread owns it.
因此,我添加了在UI線程上創建圖像的代碼。但是現在,當代碼到達<-- null
指示的行時,變量bytes
突然變爲空。在執行進入匿名函數之前,它不是null。 (我用調試器檢查過)
有誰知道這是爲什麼? Google不是很有幫助。
將變量類型bytes
更改爲var
沒有什麼區別。
的片斷提供任何沒有暗示。回到原來的方法,不要忘記調用BitmapImage的Freeze()方法,這樣你就不會再有這種異常了。 –
謝謝! img.EndInit()之後的img.Freeze()確實修復了底層問題。 – Jan