最近幾天我一直在處理backgroundWorker的問題。我一直在瀏覽MSDN上的論壇和文檔,但仍然沒有找到答案,所以現在我想問你聰明的人。長篇小說,我有一個自定義的用戶控件,包含一個ScrollViewer內的WrapPanel組件。 WrapPanel包含一些滾動到視圖中時通知的元素。 然後這些元素應該加載並顯示一個圖像,這就是問題出現的地方。爲了不鎖定gui線程,我將圖像加載到BackgroundWorker中,但GUI無論如何都阻塞了。這是代表包含在WrapPanel的元素的類代碼:在BackgroundWorker中加載圖片
class PictureThumbnail : INotifyingWrapPanelElement
{
private string path;
private Grid grid = null;
private BackgroundWorker thumbnailBackgroundCreator = new BackgroundWorker();
private delegate void GUIDelegate();
private Image thumbnailImage = null;
public PictureThumbnail(String path)
{
this.path = path;
visible = false;
thumbnailBackgroundCreator.DoWork += new DoWorkEventHandler(thumbnailBackgroundCreator_DoWork);
}
void thumbnailBackgroundCreator_DoWork(object sender, DoWorkEventArgs e)
{
BitmapImage bi = LoadThumbnail();
bi.Freeze(); //If i dont freeze bi then i wont be able to access
GUIDelegate UpdateProgressBar = delegate
{
//If this line is commented out the GUI does not stall. So it is not the actual loading of the BitmapImage that makes the GUI stall.
thumbnailImage.Source = bi;
};
grid.Dispatcher.BeginInvoke(UpdateProgressBar);
}
public void OnVisibilityGained(Dispatcher dispatcher)
{
visible = true;
thumbnailImage = new Image();
thumbnailImage.Width = 75;
thumbnailImage.Height = 75;
//I tried setting the thumbnailImage.Source to some static BitmapImage here, and that does not make the GUI stall. So it is only when it is done through the GUIDelegate for some reason.
grid.Children.Add(thumbnailImage);
thumbnailBackgroundCreator.RunWorkerAsync();
}
private BitmapImage LoadThumbnail()
{
BitmapImage bitmapImage = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri(path);
bitmapImage.DecodePixelWidth = 75;
bitmapImage.DecodePixelHeight = 75;
bitmapImage.EndInit();
return bitmapImage;
}
}
我加入的代碼一些評論解釋一些東西,我想,什麼導致我有。但我會在這裏再寫一遍。如果我只是在backgroundWorker中加載BitmapImage,但不將其作爲thumbnailImage的源應用,GUI不會停頓(但不會顯示明顯的圖像)。另外,如果我在OnVisibilityGained方法中將thumbnailImage的Source設置爲一些預加載的靜態BitmapImage(所以在GUI線程中),那麼GUI不會停止,因此它不是Image.Source的實際設置,它是罪魁禍首。
可能的重複[加載圖像停止問題](http://stackoverflow.com/questions/12103884/loading-image-stops-issue) –
它停滯,因爲ThumbnailImage從您的線程更新。 Id建議如果你有一個updateImage(BitmapImage i),如果你用bi變量調用它,它將停止拖延。 – BugFinder
@Jason,回答詳細說明解決方案是使用BackgroundWorker,這個問題詳細描述了使用BackgroundWorker的問題。顯然,BackgroundWorker問題的答案不能用於BackgroundWorker。 –