2013-05-22 47 views
2

使用此代碼,使用必須等到所有圖像加載完畢。我想要將這些圖像異步加載到列表框中,以便用戶不必等待。我怎麼做?如何將圖像異步加載到列表框中?

public photos() 
    { 
     InitializeComponent(); 
     refreshView(); 
    } 

    private void refreshView() 
    { 
     string[] fileNames = storage.GetFileNames(); 
     for (int i = 0; i < fileNames.Length; i++) 
     { 
      image = new Image(); 
      FileStream jpegStream = storage.OpenFile(fileNames[i], FileMode.Open, FileAccess.Read); 
      image.Source = PictureDecoder.DecodeJpeg(jpegStream, 200, 200); 
      jpegStream.Dispose(); 
      photoList.Items.Add(image); 
     } 
    } 
+0

使用BackgroundWorkerThread。 – nothrow

+1

也不要刷新構造函數中的視圖。使用OnLoad或類似的東西。 – wonko79

+0

歡迎來到Stackoverflow。沒有必要在標題中加入標籤。請閱讀http://meta.stackexchange.com/q/19190/147072瞭解更多信息。 – Patrick

回答

3

你可以使用一個BackgroundWorker

BackgroundWorker bw = new BackgroundWorker(); 
bw.DoWork += (o, args) => 
    { 
     //now you have a choice: get all images and add when all are retrieved, 
     //or get images asynchronously here too... 
     //probably best to do the latter: 

     string[] fileNames = storage.GetFileNames(); 
     Parallell.ForEach(fileNames, file => 
     { 
      Image image = new Image(); 
      using(FileStream jpegStream = storage.OpenFile(fileNames[i], FileMode.Open, FileAccess.Read)) 
      { 
       image.Source = PictureDecoder.DecodeJpeg(jpegStream, 200, 200); 
      } 
      Dispatcher.BeginInvoke(() => photoList.Items.Add(image)); 
     } 
    }; 
bw.RunWorkerAsync(); 
+0

更好的用戶界面與讀取圖像,添加圖像比讀取所有圖像,然後添加?如果很多大圖像讀取所有圖像可能需要時間? – Ricibob

+0

@Ricibob好點,會編輯替代 –

+0

我總是背景與UI的背景互動。工作完成之前,表格可能會被關閉。 Dispatcher.BeginInvoke(()=> if(!photoList.IsDisposed)photoList.Items.Add(image));' –