C#Async StreamReader并放入ListBox

时间:2015-03-27 13:38:46

标签: c# .net wpf asynchronous async-await

我正在构建一个工具,用于从远程服务器读取数据并将其放入列表框中。 该工具从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行并使我的工具冻结直到进程结束,所以我想在Async中执行它并在实际中查看我的列表框中的时间结果,并没有让工具冻结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。

1 个答案:

答案 0 :(得分:1)

我建议使用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();
  }
}
相关问题