将图像从 Url 异步加载到 PictureBox

Asynchronously Load an Image from a Url to a PictureBox

我想在 windows 表单应用程序上从网络加载图像, 一切都很好,代码工作正常,但问题是应用程序停止工作,直到加载完成。 我想查看和使用应用程序 而无需等待加载

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);
}

解决方法如下:

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;
});

PictureBox 控件内置了对异步加载图像的支持。您不需要使用 BackgroundWorker 或 async/await。它还可以从 URL 加载图像,因此您不需要使用网络请求。

您可以简单地使用 LoadAsync method or ImageLocation property of PictureBox. The value of WaitOnLoad 属性 应该是 false,这是默认值。

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

相当于:

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