Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c# - Asynchronously Load an Image from a Url to a PictureBox

I want to load image from the web on windows forms application, Everything is good and code works fine, but the problem is the app stop working until the loading goes to finish. I want to see and work with app without waiting to loading .

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the solution:

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

Here is how to call the above solution:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...