使用WebClient将同时下载转换为HttpClient

时间:2019-12-16 19:09:59

标签: c# httpclient webclient

我有一个WinForms应用程序,该应用程序创建了几个对象,每个对象都有其自己的WebClient并在其构造函数上调用DownloadStringAsync。调用回调DownloadStringAsyncComplete时,显示内容将更新。 我想在此保留的主要方面是能够同时执行多个请求,因为每个请求都需要几秒钟。 如何使用HttpClient完成此操作? 我等不及GetAsync,但是,如何知道每个响应何时到达? 如果我确实等待GetAsync,那么它们将一个接一个地执行,整个过程将花费很多时间...

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net;

namespace RequestTest
{
    public partial class Form1 : Form
    {
        List<Requester> requesters;

        public Form1()
        {
            InitializeComponent();

            requesters = new List<Requester>();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 20; i++)
            {
                requesters.Add(new Requester(this));
            }
        }

        public void SomeoneCompletedDownload()
        {
            textBox1.AppendText("sample text");
        }
    }

    public class Requester
    {
        Form1 caller;

        public Requester(Form1 _caller)
        {
            caller = _caller;

            var client = new WebClient();
            client.DownloadStringCompleted += DownloadCompleted;
            client.DownloadStringAsync(new Uri("some-url"));
        }

        private void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            caller.SomeoneCompletedDownload();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好的,我找到了自己的答案。 我只是将请求移到了等待的方法上。

方法本身等待响应并调用回调。

但是当调用该方法时,我并不等待它完成。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Http;

namespace RequestTest
{
    public partial class Form1 : Form
    {
        List<Requester> requesters;

        DateTime start;
        int counter;

        public Form1()
        {
            InitializeComponent();

            requesters = new List<Requester>();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            start = DateTime.Now;

            for (int i = 0; i < 30; i++)
            {
                requesters.Add(new Requester(this, i + 1));

                // only one of the following 3 lines should be uncommented
                //requesters[i].RequestWeb(); // this uses the old WebClient (~ 12 sec)
                //await requesters[i].RequestHttp(); // this takes forever since requests are executed one at a time (~ 86 sec)
                _ = requesters[i].RequestHttp(); // <-- This is the way to go for my app. Dispatch the request and continue executing discarding the result. Callback is called in the same method. (~ 13 sec, consistent with option #1)
            }
        }

        public void SomeoneCompletedDownload(string page)
        {
            var elapsed = DateTime.Now - start;
            counter++;
            textBox1.AppendText($"#{counter}: Page {page} finished after {elapsed.TotalSeconds.ToString("N2")} seconds.\r\n");
        }
    }

    public class Requester
    {
        Form1 caller;
        string page;
        string url;

        public Requester(Form1 _caller, int _page)
        {
            caller = _caller;
            page = _page.ToString();

            url = "https://www.youtube.com/";
        }

        public void RequestWeb()
        {
            var client = new WebClient();
            client.DownloadStringCompleted += DownloadCompleted;
            client.DownloadStringAsync(new Uri(url));
        }

        public async Task RequestHttp()
        {
            var client = new HttpClient();
            var response = await client.GetAsync(url);
            caller.SomeoneCompletedDownload(page);
        }

        private void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            caller.SomeoneCompletedDownload(page);
        }
    }
}