C# Async StreamReader 并放入 ListBox

C# Async StreamReader and put in ListBox

我正在构建一个从远程服务器读取数据并将其放入列表框中的工具。 该工具从 TXT 文件中获取输入,以 GET 方式传递给远程服务器,然后将结果返回到列表框中。 例子: 我在 TXT 中有一个列表,其中包含以下几行(实际上它们超过 12.000 行,而且还会增加): -Foo -Abc -Def

所以工具每行调用远程服务器:

http://remote-server.com/variable=Foo
*GET RESULT BACK AND PUT IN LISTBOX*
http://remote-server.com/variable=Abc
*GET RESULT BACK AND PUT IN LISTBOX*
http://remote-server.com/variable=Def
*GET RESULT BACK AND PUT IN LISTBOX*

它工作正常,问题是它需要很多时间,因为如前所述,该列表包含超过 12.000 行并使我的工具冻结直到过程结束,所以我想在异步中进行并查看在我的列表框中实时显示结果,不要让工具冻结 15 分钟!!

按照我的代码:

            var lines = File.ReadAllLines("List.txt");
        foreach (var line in lines)
        {
        string urlAddress = ("http://remote-server.com/variable=" + line);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;

            if (response.CharacterSet == null)
            {
                readStream = new StreamReader(receiveStream);
            }
            else
            {
                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
            }

            string data = readStream.ReadToEnd();
            if(data=="")
            {
                listBox1.Items.Add("0");
                response.Close();
                readStream.Close();
            }
            else { 
            listBox1.Items.Add(data);
            response.Close();
            readStream.Close();
            }
        }
        }

因为,我真的不知道从何说起。我试图阅读一些教程,但我真的不明白如何将异步应用于此操作,我从未使用过它。 我尝试用以下内容替换 streamreader:

string line = await reader.ReadLineAsync();

但它不起作用。 寻找方法:-) 谢谢大家! 祝大家有个美好的一天。

G.

我推荐使用 HttpClient,与 await 一起使用更容易:

using (var client = new HttpClient())
using (var reader = new StreamReader("List.txt"))
{
  var line = await reader.ReadLineAsync();
  while (line != null)
  {
    var urlAddress = ("http://remote-server.com/variable=" + line);
    var result = await client.GetStringAsync(urlAddress);
    listBox1.Items.Add(result == "" ? "0" : result);

    line = await reader.ReadLineAsync();
  }
}