2010-11-13 104 views

回答

2

使用ThreadPool從數據庫加載圖像。

所以,這樣的事情:

private void button1_Click(object sender, RoutedEventArgs e) 
{ 
    ThreadPool.QueueUserWorkItem(LoadImage, new LoadImageRequest { ImageName = "Image.png", Control = image1 }); 
} 

private void LoadImage(object state) 
{ 
    var request = (LoadImageRequest)state; 

    byte[] data = ...; // load bytes from the database using request.ImageName 

    using (var stream = new MemoryStream(data)) 
    { 
     var imageSource = BitmapFrame.Create(stream); 

     Dispatcher.BeginInvoke(
      new Action<ImageSource>(p => request.Control.Source = p), imageSource 
     ); 
    } 
} 

private class LoadImageRequest 
{ 
    public string ImageName; 
    public Image Control; 
} 
+0

尼斯的答案,但我忘了說我不能使用調度員(或我不知道怎麼做),我加載從圖像類。 – cyrianox 2010-11-13 09:49:35

+0

您必須使用調度程序。這是沒有辦法的。如果您從不同的線程加載圖像(異步),只有一種方法可以將圖像傳回UI,並通過調度程序。這個例子顯示瞭如何。 – 2010-11-13 09:53:44