2016-06-11 54 views
1

我想從窗體窗體應用程序的web上加載圖像, 一切都很好,代碼可以正常工作,但問題是應用程序停止工作,直到加載完成。 我想查看並使用應用程序而無需等待加載將圖像從Url異步加載到PictureBox

PictureBox img = new System.Windows.Forms.PictureBox(); 
var request = WebRequest.Create(ThumbnailUrl); 

using (var response = request.GetResponse()) 
using (var stream = response.GetResponseStream()) 
{ 
    img.Image = Bitmap.FromStream(stream); 
} 
+0

時間來研究'BackgroundWorker'和'asnyc'。 –

+0

謝謝你,我現在搜索 – ara

+0

做一個背景工作'dowork'事件而不是 – Rahul

回答

4

這裏是解決方案:

public async Task<Image> GetImageAsync(string url) 
{ 
    var tcs = new TaskCompletionSource<Image>(); 
    Image webImage = null; 
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); 
    request.Method = "GET"; 
    await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null) 
     .ContinueWith(task => 
     { 
      var webResponse = (HttpWebResponse) task.Result; 
      Stream responseStream = webResponse.GetResponseStream(); 
      if (webResponse.ContentEncoding.ToLower().Contains("gzip")) 
       responseStream = new GZipStream(responseStream, CompressionMode.Decompress); 
      else if (webResponse.ContentEncoding.ToLower().Contains("deflate")) 
       responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); 

      if (responseStream != null) webImage = Image.FromStream(responseStream); 
      tcs.TrySetResult(webImage); 
      webResponse.Close(); 
      responseStream.Close(); 
     }); 
    return tcs.Task.Result; 
} 

下面是如何調用上面的解決方案:異步

PictureBox img = new System.Windows.Forms.PictureBox(); 
var result = GetImageAsync(ThumbnailUrl); 
result.ContinueWith(task => 
{ 
    img.Image = task.Result; 
}); 
+0

你錯過了'**)**'之類的東西,因爲代碼不起作用 – ara

+0

@ara,我檢查代碼並修復它 –

+0

所以,謝謝你,這真是太棒了,dameeeet garm yaser jan – ara

2

PictureBox控制內置了支持加載圖像。您不需要使用BackgroundWorker或異步/等待。它也可以從URL加載圖像,所以你不需要使用網絡請求。

您可以簡單地使用LoadAsync方法或ImageLocation屬性PictureBoxWaitOnLoad屬性的值應該是false,這是默認值。

pictureBox1.LoadAsync("https://i.stack.imgur.com/K4tAc.jpg"); 

它等同於:

pictureBox1.ImageLocation = "https://i.stack.imgur.com/K4tAc.jpg";