Asynchronously Load an Image from a Url to a PictureBox

前端 未结 2 566
时光说笑
时光说笑 2020-12-19 23:08

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 fin

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 00:07

    Here is the solution:

    public async Task GetImageAsync(string url)
    {
        var tcs = new TaskCompletionSource();
        Image webImage = null;
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        request.Method = "GET";
        await Task.Factory.FromAsync(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;
    });
    

提交回复
热议问题